utils

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2023 License: MIT Imports: 4 Imported by: 2

README

Utilities for Golang

Test Go Report Card codecov Latest version License Badge Go Reference

A set of utilities functions for Golang.

PLEASE NOTE: This package is working with Go 1.18 and later versions.

Installation

You can install this package with go get command:

go get -u github.com/ghosind/utils

Getting Started

Handle Pointers

With the Pointer method, you can easy to get a pointer that points to any value you want.

str := "Hello world" // string
// get the pointer of the string, it equal to strp := &str
strp := utils.Pointer(str) // string pointer, and it point to str
log.Print(*strp) // Hello world

// It's also working for literal values
intp := utils.Pointer(1)
// You can't do:
// intp := &1
log.Print(*intp) // 1

You can also use Value or ValueWithDefault to get the value of the pointer. For nil pointer, Value method will return the zero value of the type, and ValueWithDefault method will return the default value you set.

utils.Value(strp) // Hello world
utils.ValueWithDefault(str, "Default") // Hello world

strp = nil
utils.Value(strp) // "" (empty string)
utils.ValueWithDefault(str, "Default") // Default
Conditional Expression

Golang does not provided ternary operator (?:), but you can use utils.Conditional or utils.ConditionalExpr to make it like a ternary expression.

a := 1
b := 2
bigger := utils.Conditional(a > b, a, b) // a > b ? a : b
// bigger: 2

Available Utilities

Conditional
  • Conditional: An alternative of ternary operator, same of cond ? trueExpr : falseExpr.

  • ConditionalExpr: An alternative to the conditional (ternary) operator (?:), it'll run expression by the conditional result.

  • Max: Gets the maximum value between the two values.

  • MaxN: Returns the maximum value in the list and returns the zero value of the type if no parameter.

  • Min: Gets the minimum value between the two values.

  • MinN: Returns the minimum value in the list and returns the zero value of the type if no parameter.

Error Handling
  • Try: Recoverable function container.

  • TryCatch: An alternative of try...catch...finally statement.

Math
  • Matrix: Creates and initializes a n*m matrix.
Map Manipulation
  • CloneMap: Creates a new map, and copies all the keys and their value from the source map.

  • CopyMap: Copies all keys and their value from the source map into the destination map.

Type
  • IsComparableType: Check the type of value is comparable or not.

  • IsSameType: Compares two values' type.

  • IsSameRawType: Compares two values' type without pointer.

  • TypeOf: Gets the type of the value represented in string.

  • RawTypeOf: Gets the type string name without pointer.

  • GetElem: Gets element without pointer.

Pointer and Value
  • Pointer: Gets the pointer of a value.

  • PointerWithDefault: Gets the pointer if it is not nil, or the default pointer.

  • Value: Gets the value of a pointer, or the zero value of the type if the pointer is nil.

  • ValueWithDefault: Gets the value of a pointer, or the default value if the pointer is nil.

  • PointerSlice: Converts a slice to a pointer slice.

  • ValueSlice: Converts a pointer slice to a slice.

  • PointerMap: Converts a map to a pointer map.

  • ValueMap: Converts a pointer map to a map.

License

Distributed under the MIT License. See LICENSE file for more information.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilDest means the destination variable is empty.
	ErrNilDest error = errors.New("destination is nil")

	// ErrNilFunc means the function from parameter is nil.
	ErrNilFunc error = errors.New("function is nil")
)

Functions

func CloneMap added in v0.1.3

func CloneMap[K comparable, V any](src map[K]V) map[K]V

CloneMap creates a new map, and copies all the keys and their value from the source map into the new map. It will return nil if the source map is nil.

oldMap := map[string]int{ "a": 1, "b": 2 }
newMap := CloneMap(oldMap)
log.Print(newMap)
// [a:1 b:2]

func Conditional

func Conditional[T any](cond bool, trueExpr, falseExpr T) T

Conditional is an alternative to the conditional (ternary) operator (?:).

a := 1
b := 2
Conditional(a > b, a, b) // 2

func ConditionalExpr added in v0.1.1

func ConditionalExpr[T any](cond bool, trueExpr, falseExpr func() T) T

ConditionalExpr is an alternative to the conditional (ternary) operator (?:), it'll run expression by the conditional result.

var strp *string // nil
ConditionalExpr(strp == nil,
  func() string { return "" },
  func() string { return *strp },
) // ""

strp = Pointer("hello")
ConditionalExpr(strp == nil,
  func() string { return "" },
  func() string { return *strp },
) // "hello"

func CopyMap added in v0.1.3

func CopyMap[K comparable, V any](dest, src map[K]V) error

CopyMap copies all keys and their value from the source map into the destination map, and it will overwrite the old value in the destination map if the key has existed. The function will return a nil destination error if the source map is not nil and the destination map is nil.

src := map[string]int{ "a": 1, "b": 2 }
dest := map[string]int{ "a": 10, "c": 3 }
CopyMap(dest, src)
log.Print(dest)
// [a:1 b:2 c:3]

func GetElem

func GetElem(o any) any

GetElem returns the element without pointer.

v := 1
vp := &v
GetElem(v) // 1
GetElem(vp) // 1

func IsComparableType added in v0.2.0

func IsComparableType(v any) bool

IsComparableType gets the value type and checks whether the type is comparable or not.

IsComparableType(1) // true for int
IsComparableType(1.0) // true for float64
IsComparableType("") // true for string
IsComparableType(nil) // false for nil
IsComparableType(SomeStruct{}) // false for struct
IsComparableType(&SomeStruct{}) // false for pointer

func IsSameRawType

func IsSameRawType(v1, v2 any) bool

IsSameRawType compares two values' type without pointer.

v1 := 1 // int
v2 := 2 // int
v3 := Pointer(3) // *int
IsSameRawType(v1, v2) // true
IsSameRawType(v1, v3) // true

func IsSameType

func IsSameType(v1, v2 any) bool

IsSameType compares two values' type.

v1 := 1 // int
v2 := 2 // int
v3 := Pointer(3) // *int
IsSameType(v1, v2) // true
IsSameType(v1, v3) // false

func Matrix added in v0.2.0

func Matrix[T any](rows, columns int, values ...T) [][]T

Matrix creates a rows * columns matrix, and initialize it with the values.

Matrix[int](2, 2) // [][]int{{0, 0}, {0, 0}}
Matrix(2, 2, 1, 2, 3, 4) // [][]int{{1, 2}, {3, 4}}
Matrix(2, 2, 1, 2, 3) // [][]int{{1, 2}, {3, 0}}

func Max

func Max[T constraints.Ordered](v1, v2 T) T

Max returns the maximum value between v1 and v2.

Max(1, 2) // 2
Max(1.0, 2.0) // 2.0
Max("str1", "str2") // "str2"

func MaxN added in v0.2.0

func MaxN[T constraints.Ordered](values ...T) T

`MaxN` returns the maximum value in the list and returns the zero value of the type if no parameter.

MaxN[int]() // 0
MaxN(2, 1) // 2
MaxN(3, 2, 1, 0, 2, 4) // 4

func Min

func Min[T constraints.Ordered](v1, v2 T) T

Min returns the minimum value between v1 and v2.

Min(1, 2) // 1
Min(1.0, 2.0) // 1.0
Min("str1", "str2") // "str1"

func MinN added in v0.2.0

func MinN[T constraints.Ordered](values ...T) T

`MinN` returns the minimum value in the list and returns the zero value of the type if no parameter.

MinN[int]() // 0
MinN(1, 2) // 1
MinN(3, 2, 1, 0, 2, 4) // 0

func Pointer

func Pointer[T any](v T) *T

Pointer returns a pointer to the value passed in.

v := 1 // type is int
vp := Pointer(v) // type is *int, *vp = 1
TypeOf(vp) // "*int"

func PointerMap

func PointerMap[K comparable, V any](src map[K]V) map[K]*V

PointerMap converts a map of values into a map of pointers.

func PointerSlice

func PointerSlice[T any](src []T) []*T

PointerToSlice converts a slice of values into a slice of pointers.

func PointerWithDefault added in v0.2.0

func PointerWithDefault[T any](v *T, defaultValue *T) *T

PointerWithDefault returns the pointer if it is not nil, or the default pointer.

v := Pointer(1)
dv := Pointer(2)
PointerWithDefault(v, dv) // &1
v = nil
PointerWithDefault(v, dv) // &2

func RawTypeOf

func RawTypeOf(v any) string

RawTypeOf returns the type string name without pointer.

RawTypeOf(nil) // "<nil>"
RawTypeOf(1) // "int"
RawTypeOf("test") // "string"
RawTypeOf(&http.Client{}) // "http.Client"

func Try added in v0.2.0

func Try(fn func() error) (err error)

Try provided a recoverable function container to handle both return error and panic error.

Try(func() error {
  panic("some error")
})
// some error

func TryCatch added in v0.2.0

func TryCatch(
	tryStmt func() error,
	catchStmt func(error),
	finallyStmt ...func(),
) error

TryCatch is an alternative to the `try...catch...finally` statement. This function requires a `try` statement function and a `catch` statement function, and it accepts an optional `finally` statement function.

This function will execute the try statement function, and call the catch statement function if the try function returns an error or panic. It will always perform the `finally` statement function whether the try function is successful or not if the `finally` function is not nil. However, if the `catch` function panics, this TryCatch statement will also panic, and finally function will never run.

err := TryCatch(
  func() error {
    // Do something as try statement
    return nil
  },
  func (err error) {
    // Do something as catch statement
  },
  func () {
    // An optional finally statement
  },
)

func TypeOf added in v0.1.1

func TypeOf(v any) string

TypeOf returns the type of the value represented in string.

TypeOf(nil) // "<nil>"
TypeOf(1) // "int"
TypeOf("test") // "string"
TypeOf(&http.Client{}) // "*http.Client"

func Value

func Value[T any](v *T) T

Value returns the value of a pointer, or the zero value of the type if the pointer is nil.

var p1 *string // nil
var p2 *string = Pointer("hello")
Value(p1) // ""
Value(p2) // "hello"

func ValueMap

func ValueMap[K comparable, V any](src map[K]*V) map[K]V

ValueMap converts a map of pointers into a map of values, and it'll set the value to the zero value of the type if the pointer is point to nil.

m1 := map[string]*int{ "a": Pointer(1), "b": nil, "c": Pointer(3) }
m2 := ValueMap(m1)
// [a:1, b:0, c:3]

func ValueSlice

func ValueSlice[T any](src []*T) []T

ValueSlice converts a slice of pointers into a slice of values, and it'll set the value to the zero value of the type if the pointer is point to nil.

s1 := []*string{Pointer("Hello"), nil, Pointer("World")}
s2 := ValueSlice(s1)
// ["Hello", "", "World"]

func ValueWithDefault

func ValueWithDefault[T any](val *T, defaultVal T) T

ValueWithDefault returns the value passed in if it is not nil, otherwise returns the default value.

var p1 *string // nil
var p2 *string = Pointer("hello")
ValueWithDefault(p1, "default") // "default"
ValueWithDefault(p2, "default") // "hello"

Types

This section is empty.

Jump to

Keyboard shortcuts

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