xgo

package module
v0.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2024 License: MIT Imports: 7 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

xgo - Useful Go library

Test CLI Godoc Go Report Card GitHub license

The xgo contains various useful features for gohers.

Features

  • Deep copy
  • Contains
  • Chunk
  • Exponential backoff
  • Struct to map
  • Obtain pointers to types
Protobuf support

There is an extension package that supports deep copying Protobuf timestamp types.

Install

$ go get github.com/glassonion1/xgo

Import

import "github.com/glassonion1/xgo"

Usage

Deep copy

field-to-field copying based on matching names.

In layered architecture, there are times when we need to copy values between structs that have different types but share the same field names. The DeepCopy function is designed to be used in such scenarios.

Support for copying data:

  • from struct to struct
  • from struct to pointer
  • from pointer to struct
  • from slice to slice
from struct to struct
package xgo_test

import (
    "fmt"
    "time"

    "github.com/glassonion1/xgo"
)

type FromModel struct {
    ID         string `copier:"Id"`
    Name       string
    CreatedAt  time.Time
    UpdatedAt  *time.Time
}
type ToModel struct {
    Id         string
    Name       string
    CreatedAt  time.Time
    UpdatedAt  *time.Time
}

func Example() {
    now := time.Date(2025, 6, 1, 0, 0, 0, 0, time.UTC)
    from := FromModel{
        ID:        "xxxx",
        Name:      "R2D2",
        CreatedAt: now,
        UpdatedAt: &now,
    }
    to := &ToModel{}
    err := xgo.DeepCopy(from, to)
    if err != nil {
        // handles error
    }
    fmt.Println("ToModel object:", to)

    // Output: ToModel object: &{xxxx R2D2 2025-06-01 00:00:00 +0000 UTC 2025-06-01 00:00:00 +0000 UTC}
}
from slice to slice
type FromModel struct {
    ID         string
    Name       string
}
type ToModel struct {
    ID         string
    Name       string
}

func Example() {
    from := []FromModel{
        {
            ID: "xxxx1",
            Name: "R2D2",
        },
    {
            ID: "xxxx2",
            Name: "C3PO",
        },
    }
    to := &[]ToModel{}
    err := xgo.DeepCopy(from, to)
    if err != nil {
        // handles error
    }
    fmt.Println("ToModel object:", to)
    
    // Output: ToModel object: &[{xxxx1 R2D2} {xxxx2 C3PO}]
}
Contains

Contains method for a slice.

// slice of int32
containsInt32 := xgo.Contains([]int32{1, 2, 3, 4, 5}, 3)
fmt.Println("contains int32:", containsInt32)

// slice of int
containsInt := xgo.Contains([]int{1, 2, 3, 4, 5}, 2)
fmt.Println("contains int:", containsInt)

// slice of float64
containsFloat64 := xgo.Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
fmt.Println("contains float64:", containsFloat64)

// slice of string
containsString := xgo.Contains([]string{"r2d2", "c3po", "bb8"}, "c3po")
fmt.Println(containsString) // -> true

// slice of struct
type hero struct {
    ID   string
    Name string
}
list := []hero{
    hero{
        ID:   "1",
        Name: "Luke Skywalker",
    },
    hero{
        ID:   "2",
        Name: "Han Solo",
    },
    hero{
        ID:   "3",
        Name: "Leia Organa",
    },
}
target := hero{
	ID:   "2",
	Name: "Han Solo",
}
containsStruct := xgo.Contains(list, target)
fmt.Println("contains struct:", containsStruct)

// Output:
// contains int32: true
// contains int: true
// contains float64: true
// contains string: true
// contains struct: true
ToPtr

Obtain pointers to types

type Vegetables string

const (
	Pea     Vegetables = "Pea"
	Okra    Vegetables = "Okra"
	Pumpkin Vegetables = "Pumpkin"
)

type Model struct {
	ID        *int
	Name      *string
	Material  *Vegetables
	CreatedAt *time.Time
}

func ExampleToPtr() {
	obj := Model{
		ID:        xgo.ToPtr(123),
		Name:      xgo.ToPtr("R2D2"),
		Material:  xgo.ToPtr(Pea),
		CreatedAt: xgo.ToPtr(time.Date(2020, 6, 1, 0, 0, 0, 0, time.UTC)),
	}
	fmt.Println("object:", obj)
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Chunk

func Chunk[T any](list []T, chunkSize int) [][]T

func ChunkIndex added in v0.0.2

func ChunkIndex(length int, chunkSize int) <-chan ChunkedIndex

ChunkedIndex divides index into chunks

func Contains

func Contains[T any](list []T, elem T) bool

Contains returns true if an element is present in a slice

Example
package main

import (
	"fmt"

	"github.com/glassonion1/xgo"
)

func main() {
	// slice of int32
	containsInt32 := xgo.Contains([]int32{1, 2, 3, 4, 5}, 3)
	fmt.Println("contains int32:", containsInt32)

	// slice of int
	containsInt := xgo.Contains([]int{1, 2, 3, 4, 5}, 2)
	fmt.Println("contains int:", containsInt)

	// slice of float64
	containsFloat64 := xgo.Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
	fmt.Println("contains float64:", containsFloat64)

	// slice of string
	containsString := xgo.Contains([]string{"r2d2", "c3po", "bb8"}, "c3po")
	fmt.Println("contains string:", containsString) // -> true

	// slice of struct
	type hero struct {
		ID   string
		Name string
	}
	list := []hero{
		{
			ID:   "1",
			Name: "Luke Skywalker",
		},
		{
			ID:   "2",
			Name: "Han Solo",
		},
		{
			ID:   "3",
			Name: "Leia Organa",
		},
	}
	target := hero{
		ID:   "2",
		Name: "Han Solo",
	}
	containsStruct := xgo.Contains(list, target)
	fmt.Println("contains struct:", containsStruct)

}
Output:
contains int32: true
contains int: true
contains float64: true
contains string: true
contains struct: true

func DeepCopy

func DeepCopy(srcModel interface{}, dstModel interface{}) error

DeepCopy

Example (Slice)
package main

import (
	"fmt"

	"github.com/glassonion1/xgo"
)

func main() {
	type FromModel struct {
		ID   string
		Name string
	}
	type ToModel struct {
		ID   string
		Name string
	}
	from := []FromModel{
		{
			ID:   "xxxx1",
			Name: "R2D2",
		},
		{
			ID:   "xxxx2",
			Name: "C3PO",
		},
	}
	to := &[]ToModel{}
	err := xgo.DeepCopy(from, to)
	if err != nil {
		// handles error
	}
	fmt.Println("ToModel object:", to)

}
Output:
ToModel object: &[{xxxx1 R2D2} {xxxx2 C3PO}]
Example (Struct)
package main

import (
	"fmt"
	"time"

	"github.com/glassonion1/xgo"
)

func main() {
	type FromModel struct {
		ID        string `copier:"Id"`
		Name      string
		CreatedAt time.Time
		UpdatedAt *time.Time
	}

	type ToModel struct {
		Id        string
		Name      string
		CreatedAt time.Time
		UpdatedAt *time.Time
	}

	now := time.Date(2025, 6, 1, 0, 0, 0, 0, time.UTC)
	from := FromModel{
		ID:        "xxxx",
		Name:      "R2D2",
		CreatedAt: now,
		UpdatedAt: &now,
	}
	to := &ToModel{}
	err := xgo.DeepCopy(from, to)
	if err != nil {
		// handles error
	}
	fmt.Println("ToModel object:", to)

}
Output:
ToModel object: &{xxxx R2D2 2025-06-01 00:00:00 +0000 UTC 2025-06-01 00:00:00 +0000 UTC}

func DeepCopyWithCustomSetter added in v0.0.8

func DeepCopyWithCustomSetter(
	srcModel interface{},
	dstModel interface{},
	customSetter SetCustomField,
) error

DeepCopy with custom setter

func FromPtr added in v0.0.8

func FromPtr[T any](x *T) T

FromPtr returns the pointer value or empty.

func IndexOf added in v0.0.4

func IndexOf[T any](list []T, elem T) int

IndexOf returns index of slice

func IsBlank

func IsBlank(value reflect.Value) bool

IsBlank determines whether the object is blank or sero value

func IsFirstUpper

func IsFirstUpper(v string) bool

IsFirstUpper determines whether the first letter is upper case

func Map added in v0.0.6

func Map[S, D any](input []S, f func(S) (D, error)) ([]D, error)

func New deprecated added in v0.0.6

func New[T any](x T) *T

Deprecated: Use ToPtr instead.

func StructToMap

func StructToMap(data interface{}) map[string]interface{}

StructToMap converts a struct to map

func ToPtr added in v0.0.8

func ToPtr[T any](x T) *T

ToPtr returns a pointer copy of value.

Example
package main

import (
	"fmt"
	"time"

	"github.com/glassonion1/xgo"
)

type Vegetables string

const Pea Vegetables = "Pea"

type Model struct {
	ID        *int
	Name      *string
	Material  *Vegetables
	CreatedAt *time.Time
}

func main() {
	obj := Model{
		ID:        xgo.ToPtr(123),
		Name:      xgo.ToPtr("R2D2"),
		Material:  xgo.ToPtr(Pea),
		CreatedAt: xgo.ToPtr(time.Date(2020, 6, 1, 0, 0, 0, 0, time.UTC)),
	}
	fmt.Println("object:", obj)
}

Types

type ChunkedIndex added in v0.0.2

type ChunkedIndex struct {
	From, To int
}

Index is chunked index that contains from and to

type ExponentialBackoff

type ExponentialBackoff struct {
	// contains filtered or unexported fields
}

ExponentialBackoff represents retry with exponential backoff

func NewExponentialBackoff

func NewExponentialBackoff() *ExponentialBackoff

NewExponentialBackoff creates a NewExponentialBackoff instance

func (*ExponentialBackoff) Perform

func (eb *ExponentialBackoff) Perform(fn func() error, retryCondition func(err error) bool) error

Perform the exponential backoff algorithm

type SetCustomField added in v0.0.8

type SetCustomField func(src, dst reflect.Value) (bool, error)

Directories

Path Synopsis
xgopb module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址