A set of utilities functions for Golang.
PLEASE NOTE: This package is working with Go 1.18 and later versions.
You can install this package with go get
command:
go get -u github.com/ghosind/utils
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
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
-
Conditional
: An alternative of ternary operator, same ofcond ? 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.
Matrix
: Creates and initializes a n*m matrix.
-
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.
-
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
: 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.
Distributed under the MIT License. See LICENSE file for more information.