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
,uint
etc.
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
, whereK
are the keys, andV
are 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: true
Merges 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]V
is 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:
a
is a map of typemap[K]V
from which elements will be removed.b
is a map of typemap[K]V
containing the keys to be removed from the map "a".
Return value:
map[K]V
is 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:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
is the maximum value from the provided arguments.
Usage example:
maxValue := math.Max(1, 2, 3, 4, 5)
// maxValue: 5
Returns the minimum value from the provided arguments.
Parameters:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
is the minimum value from the provided arguments.
Usage example:
minValue := math.Min(1, 2, 3, 4, 5)
// minValue: 1
Returns the sum of all the provided values.
Parameters:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
is the sum of all the provided arguments.
Usage example:
total := math.Sum(1, 2, 3, 4, 5)
// total: 15
Package 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:
sl
is a slice of entities of typeT
, which have an id.
Return value:
[]uint
is 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:
m
is a map where the keys are of typeK
, and the values are of typeT
, which have an id.
Return value:
[]uint
is 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:
slice
is a slice of entities of typeS
.getter
is a function that takes an entity of typeS
and returns a value of typeR
, which will be added to the final slice.
Return value:
[]R
is 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:
m
is a map where the keys are of typeK
, and the values are of typeV
.getter
is a function that takes a value of typeV
and returns a value of typeR
, which will be added to the final slice.
Return value:
[]R
is 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:
tt
is a variable number of arguments of typeT
, whereT
is any type that supports comparison.
Return value:
T
is 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: nil
Package 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:
s
is a slice of elements of typeT
that needs to be converted.
Return value:
[]R
is 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:
sl
is a slice of elements of typeT
from which empty values will be removed.
Return value:
[]T
is 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:
sl
is a slice of elements of typeT
from which duplicates will be removed.
Return value:
[]T
is 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:
sl1
is the first slice of typeT
.sl2
is the second slice of typeT
.
Return value:
[]T
is 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:
sl1
is the first slice of typeT
.sl2
is the second slice of typeT
.
Return value:
[]T
is 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:
sl1
is the first slice of typeT
.sl2
is the second slice of typeT
.
Return value:
bool
—true
if 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: true
Function that checks whether a slice contains a specified value.
Parameters:
sl
is a slice of typeT
in which to search.n
is a value of typeT
that needs to be found in the slice.
Return value:
bool
—true
if the value is present in the slice, otherwisefalse
.
Usage example:
slice := []string{"apple", "banana", "cherry"}
exists := slices.Has(slice, "banana")
// exists: true
Function that trims whitespace from the beginning and end of each string in a slice of strings.
Parameters:
ss
is 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:
sl
is a slice of values of typeT
to 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:
slices
is a variable number of slices of typeT
from 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:
slices
is a variable number of slices of typeT
from 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:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
— the maximum value from the provided arguments.
Usage example:
maxValue := slices.Max([]int{1, 2, 3, 4, 5})
// maxValue: 5
Function that returns the minimum value from the provided arguments.
Parameters:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
— the minimum value from the provided arguments.
Usage example:
minValue := slices.Min([]int{1, 2, 3, 4, 5})
// minValue: 1
Function that returns the sum of all provided values.
Parameters:
n
is a variable number of arguments of typeT
, whereT
is any numeric type supported by theNumeric
interface.
Return value:
T
— the sum of all provided arguments.
Usage example:
total := slices.Sum([]int{1, 2, 3, 4, 5})
// total: 15
Package 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 UTC
Returns the midnight time for the specified location.
Parameters:
loc
— a pointer to atime.Location
structure 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 MSK
Returns 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