go-utils — is a utility library for the Go programming language. It provides convenient generic functions and tools
for working with slices, strings, time, and much more.
A package that provides common types for use in other project packages. It generalizes functions and data types to work with various value types.
- Numeric - combines all numeric types like
int,float32,uintetc.
The Numeric interface combines all numeric types like int, float32, uint, and others.
Usage example:
func Sum[T Numeric](n []T) T {
var sum T
for _, v := range n {
sum += v
}
return sum
}A package that provides functions for convenient map operations.
- Has: Checks if a map contains a given key.
- Merge: Merges two maps. Values from map "a" take precedence.
- DiffKeys: Returns map "a" without the elements from map "b".
Checks if a map contains a given key.
Parameters:
m— a map of typemap[K]V, whereKare the keys, andVare the values.key— the key to check for.
Return value:
bool—true, if the key is present in the map, otherwisefalse.
Usage example:
m := map[string]int{"one": 1, "two": 2}
exists := maps.Has(m, "two")
// exists: trueMerges two maps. Values from map "a" take precedence.
Parameters:
a— first map of type mapmap[K]V.b— second map of typemap[K]V.
Return value:
map[K]Vis a new map containing the combined elements.
Usage example:
a := map[string]int{"one": 1, "two": 2}
b := map[string]int{"two": 3, "three": 4}
merged := maps.Merge(a, b)
// merged: {"one": 1, "two": 3, "three": 4}Returns map "a" without elements from map "b".
Parameters:
ais a map of typemap[K]Vfrom which elements will be removed.bis a map of typemap[K]Vcontaining the keys to be removed from the map "a".
Return value:
map[K]Vis a new map containing elements from "a" that are not in "b".
Usage example:
a := map[string]int{"one": 1, "two": 2, "three": 3}
b := map[string]int{"two": 2, "four": 4}
diff := maps.DiffKeys(a, b)
// diff: {"one": 1, "three": 3}Package providing mathematical functions for working with numeric types.
- Max: Returns the maximum value from the provided arguments.
- Min: Returns the minimum value from the provided arguments.
- Sum: Returns the sum of all the provided values.
Returns the maximum value from the provided arguments.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
Tis the maximum value from the provided arguments.
Usage example:
maxValue := math.Max(1, 2, 3, 4, 5)
// maxValue: 5Returns the minimum value from the provided arguments.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
Tis the minimum value from the provided arguments.
Usage example:
minValue := math.Min(1, 2, 3, 4, 5)
// minValue: 1Returns the sum of all the provided values.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
Tis the sum of all the provided arguments.
Usage example:
total := math.Sum(1, 2, 3, 4, 5)
// total: 15Package providing functions for working with entities (models).
- CollectIDs: Returns a slice of identifiers from a slice of entities.
- CollectIDsFromMap: Returns a slice of identifiers from a map of entities.
- UniqueValues: Method for collecting unique values from any field of a model into a slice of the desired result type.
- UniqueValuesFromMap: Method for collecting unique values from any field of a model into a slice of the desired result type, using a map.
Returns a slice of identifiers from a slice of entities.
Parameters:
slis a slice of entities of typeT, which have an id.
Return value:
[]uintis a slice of unique identifiers.
Usage example:
type User struct {
ID uint
// other fields
}
func (u User) GetID() uint {
return u.ID
}
users := []User{{ID: 1}, {ID: 2}, {ID: 1}}
ids := CollectIDs(users)
// ids: []uint{1, 2}Returns a slice of identifiers from a map of entities that have an id.
Parameters:
mis a map where the keys are of typeK, and the values are of typeT, which have an id.
Return value:
[]uintis a slice of unique identifiers.
Usage example:
type User struct {
ID uint
// other fields
}
func (u User) GetID() uint {
return u.ID
}
userMap := map[string]User{
"user1": {ID: 1},
"user2": {ID: 2},
"user3": {ID: 1},
}
ids := CollectIDsFromMap(userMap)
// ids: []uint{1, 2}Method for collecting unique values from any field of a model into a slice of the desired result type.
Parameters:
sliceis a slice of entities of typeS.getteris a function that takes an entity of typeSand returns a value of typeR, which will be added to the final slice.
Return value:
[]Ris a slice of unique values obtained from the provided slice.
Usage example:
type Product struct {
ID uint
Name string
}
func GetProductID(p Product) uint {
return p.ID
}
products := []Product{
{ID: 1, Name: "Product A"},
{ID: 2, Name: "Product B"},
{ID: 1, Name: "Product C"},
}
uniqueIDs := UniqueValues(products, GetProductID)
// uniqueIDs: []uint{1, 2}Method for collecting unique values from any field of a model into a slice of the desired result type, using a map.
Parameters:
mis a map where the keys are of typeK, and the values are of typeV.getteris a function that takes a value of typeVand returns a value of typeR, which will be added to the final slice.
Return value:
[]Ris a slice of unique values obtained from the provided map.
Usage example:
type User struct {
ID uint
Name string
}
func GetUserName(u User) string {
return u.Name
}
users := map[string]User{
"user1": {ID: 1, Name: "Alice"},
"user2": {ID: 2, Name: "Bob"},
"user3": {ID: 3, Name: "Alice"},
}
uniqueNames := UniqueValuesFromMap(users, GetUserName)
// uniqueNames: []string{"Alice", "Bob"}Package that contains utility functions for working with various data types.
- FirstNonEmpty: Returns the first element with a non-zero value from the provided arguments.
Returns the first element with a non-zero value from the provided arguments.
Parameters:
ttis a variable number of arguments of typeT, whereTis any type that supports comparison.
Return value:
Tis the first non-zero element from the provided arguments. If all elements are zero, it returns the default value for typeT.
Usage example:
first := other.FirstNonEmpty("", "hello", "world")
// first: "hello"
firstNum := other.FirstNonEmpty(0, 1, 2)
// firstNum: 1
firstNil := other.FirstNonEmpty(nil, nil)
// firstNil: nilPackage that contains short functions for working with various data types.
- If: Returns the value of
thenif condition is true, otherwise returns the value ofotherwise. - IfFunc: Returns the result of calling
thenif condition is true, otherwise returns the result of callingotherwise(lazy evaluation). - IfFuncE: Returns the result of calling
thenif condition is true, otherwise returns the result of callingotherwise(lazy evaluation with error).
Returns the value of then if condition is true, otherwise returns the value of otherwise.
Parameters:
condition— a boolean value that determines which value to return.then— a value of typeTthat will be returned ifconditionistrue.otherwise— a value of typeTthat will be returned ifconditionisfalse.
Return value:
T— the value ofthenifconditionistrue, otherwise the value ofotherwise.
Usage example:
result := other.If(true, "yes", "no")
// result: "yes"
value := other.If(false, 10, 20)
// value: 20Returns the result of calling then if condition is true, otherwise returns the result of calling otherwise (lazy evaluation). This function allows for lazy evaluation, meaning the functions are only called when needed.
Parameters:
condition— a boolean value that determines which function to call.then— a function that returns a value of typeTand will be called ifconditionistrue.otherwise— a function that returns a value of typeTand will be called ifconditionisfalse.
Return value:
T— the result of callingthen()ifconditionistrue, otherwise the result of callingotherwise().
Usage example:
result := other.IfFunc(true,
func() string { return expensiveOperation() },
func() string { return "default" },
)
// Only expensiveOperation() will be called
value := other.IfFunc(false,
func() int { return 100 },
func() int { return 200 },
)
// value: 200Returns the result of calling then if condition is true, otherwise returns the result of calling otherwise (lazy evaluation with error). This function allows for lazy evaluation and error handling.
Parameters:
condition— a boolean value that determines which function to call.then— a function that returns a value of typeTand an error, and will be called ifconditionistrue.otherwise— a function that returns a value of typeTand an error, and will be called ifconditionisfalse.
Return value:
T— the result of callingthen()ifconditionistrue, otherwise the result of callingotherwise().error— an error returned by the called function, ornilif no error occurred.
Usage example:
result, err := other.IfFuncE(true,
func() (string, error) { return fetchData() },
func() (string, error) { return "default", nil },
)
if err != nil {
// error handling
}
value, err := other.IfFuncE(false,
func() (int, error) { return 100, nil },
func() (int, error) { return 0, errors.New("error") },
)
// value: 0, err: errorPackage providing functions for working with slices.
- ConvertSlice: changes the type of elements in the slice.
- FilterNil: returns a slice without empty values (e.g., 0, "", etc.), modifying the original slice.
- Unique: returns a slice without duplicates, modifying the original slice.
- Union: combines two slices, excluding duplicates.
- Cross: returns a slice with values present in both slices.
- IsEqual: checks if the slices are identical, regardless of the order of elements.
- Has: checks if the slice contains a given value.
- TrimStrings: removes spaces from each element of a string slice.
- ToKeyMap: returns a map with keys equal to the values of the slice.
- SliceDiff: returns a slice containing elements present in the first slice but absent in others.
- SliceIntersect: returns a slice with unique values present in all provided slices.
- Max: returns the maximum value from the provided elements.
- Min: returns the minimum value from the provided elements.
- Sum: returns the sum of all values.
Function that changes the type of elements in a slice.
Parameters:
sis a slice of elements of typeTthat needs to be converted.
Return value:
[]Ris a new slice of elements of typeR, obtained by converting the elements from the slices.
Usage example:
newSlice := slices.ConvertSlice[int32, uint]([]int32{1, 2, 3})
// newSlice: []uint{1, 2, 3}Function that returns a slice without empty values (e.g., 0, "", etc.). Note that it modifies the original slice.
Parameters:
slis a slice of elements of typeTfrom which empty values will be removed.
Return value:
[]Tis a slice containing only non-empty values.
Usage example:
values := []int{0, 1, 2, 0, 3}
filtered := slices.FilterNil(values)
// filtered: []int{1, 2, 3}Function that returns a slice without duplicates. Note that it modifies the original slice.
Parameters:
slis a slice of elements of typeTfrom which duplicates will be removed.
Return value:
[]Tis a slice containing only unique values.
Usage example:
values := []int{1, 2, 2, 3, 4, 4}
uniqueValues := slices.Unique(values)
// uniqueValues: []int{1, 2, 3, 4}Function that combines two slices, excluding duplicates.
Parameters:
sl1is the first slice of typeT.sl2is the second slice of typeT.
Return value:
[]Tis a new slice containing unique values from both input slices.
Usage example:
slice1 := []int{1, 2, 3}
slice2 := []int{3, 4, 5}
result := slices.Union(slice1, slice2)
// result: []int{1, 2, 3, 4, 5}Function that returns a slice of values present in both input slices.
Parameters:
sl1is the first slice of typeT.sl2is the second slice of typeT.
Return value:
[]Tis a new slice containing values that are present in both input slices.
Usage example:
slice1 := []int{1, 2, 3}
slice2 := []int{2, 3, 4}
result := slices.Cross(slice1, slice2)
// result: []int{2, 3}Function that checks whether two slices are identical, regardless of the order of elements.
Parameters:
sl1is the first slice of typeT.sl2is the second slice of typeT.
Return value:
bool—trueif the slices are identical (contain the same elements in any order), otherwisefalse.
Usage example:
slice1 := []int{1, 2, 3}
slice2 := []int{3, 2, 1}
isEqual := slices.IsEqual(slice1, slice2)
// isEqual: trueFunction that checks whether a slice contains a specified value.
Parameters:
slis a slice of typeTin which to search.nis a value of typeTthat needs to be found in the slice.
Return value:
bool—trueif the value is present in the slice, otherwisefalse.
Usage example:
slice := []string{"apple", "banana", "cherry"}
exists := slices.Has(slice, "banana")
// exists: trueFunction that trims whitespace from the beginning and end of each string in a slice of strings.
Parameters:
ssis a slice of strings to be processed.
Return value:
[]string— a slice of strings where each string is trimmed of whitespace.
Usage example:
strings := []string{" apple ", " banana ", "cherry "}
trimmed := slices.TrimStrings(strings)
// trimmed: []string{"apple", "banana", "cherry"}Function that converts a slice of values into a map where the keys are the elements of the slice and the values are boolean indicating the presence of these keys.
Parameters:
slis a slice of values of typeTto be converted into a map.
Return value:
map[T]bool— a map where the keys are the elements from the slice and the values aretrue.
Usage example:
values := []string{"apple", "banana", "cherry"}
keyMap := slices.ToKeyMap(values)
// keyMap: map[string]bool{"apple": true, "banana": true, "cherry": true}Function that returns a slice containing elements that are present in the first slice but absent in the other provided slices.
Parameters:
slicesis a variable number of slices of typeTfrom which the difference will be calculated.
Return value:
[]T— a slice containing elements from the first slice that are not in the others.
Usage example:
slice1 := []int{1, 2, 3, 4}
slice2 := []int{3, 4, 5}
slice3 := []int{4, 5, 6}
result := slices.SliceDiff(slice1, slice2, slice3)
// result: []int{1, 2}Function that returns a slice of unique values present in all provided slices.
Parameters:
slicesis a variable number of slices of typeTfrom which the intersection will be calculated.
Return value:
[]T— a slice containing unique elements that are present in all of the provided slices.
Usage example:
slice1 := []int{1, 2, 3, 4}
slice2 := []int{3, 4, 5}
slice3 := []int{4, 5, 6}
result := slices.SliceIntersect(slice1, slice2, slice3)
// result: []int{4}Function that returns the maximum value from the provided arguments.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
T— the maximum value from the provided arguments.
Usage example:
maxValue := slices.Max([]int{1, 2, 3, 4, 5})
// maxValue: 5Function that returns the minimum value from the provided arguments.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
T— the minimum value from the provided arguments.
Usage example:
minValue := slices.Min([]int{1, 2, 3, 4, 5})
// minValue: 1Function that returns the sum of all provided values.
Parameters:
nis a variable number of arguments of typeT, whereTis any numeric type supported by theNumericinterface.
Return value:
T— the sum of all provided arguments.
Usage example:
total := slices.Sum([]int{1, 2, 3, 4, 5})
// total: 15Package providing functions for working with strings.
- Truncate: Truncates a string to the specified number of runes.
Truncates a string to the specified number of runes.
Parameters:
str— the string to be truncated.maxRunes— the maximum number of runes to truncate the string to.
Return value:
string— the truncated string if the length exceedsmaxRunes, otherwise the original string.
Usage example:
result := strings.Truncate("Hello, World!", 5)
// result: "Hello"Package providing functions for working with time values.
- Midnight: Returns the time corresponding to midnight for the current date in the local time zone.
- MidnightByLocation: Returns midnight time for the specified location.
- MidnightByTimeZone: Returns midnight time for the specified time zone.
Returns the time corresponding to midnight for the current date in the local time zone.
Return value:
time.Time— the time value corresponding to midnight.error— an error if there was a problem calculating the time (usually does not occur).
Usage example:
midnight, err := time.Midnight()
if err != nil {
// error handling
}
// midnight: 2024-09-20 00:00:00 +0000 UTCReturns the midnight time for the specified location.
Parameters:
loc— a pointer to atime.Locationstructure representing the time zone.
Return value:
time.Time— the time value corresponding to midnight in the specified time zone.error— an error if there was a problem calculating the time (usually does not occur).
Usage example:
loc, err := time.LoadLocation("Europe/Moscow")
if err != nil {
// error handling
}
midnight, err := time.MidnightByLocation(loc)
if err != nil {
// error handling
}
// midnight: 2024-09-20 00:00:00 +0300 MSKReturns the midnight time for the specified time zone.
Parameters:
timeZone— a string representing the name of the time zone (e.g., "Europe/Moscow").
Return value:
time.Time— the time value corresponding to midnight in the specified time zone.error— an error if there was a problem loading the time zone (e.g., if the specified time zone does not exist).
Usage example:
midnight, err := time.MidnightByTimeZone("Europe/Moscow")
if err != nil {
// error handling
}
// midnight: 2024-09-20 00:00:00 +0300 MSK