The purpose here is to have a concrete type returned, to simplify (and strengthen) client code.
Consider a custom type Nickname:
Given an array of nicknames:
nicknames := []Nickname{
"Goose",
"Ice Man",
"Maverick",
}
to obtain a slice of string, one must use CollectSlice() as follows:
a, err := CollectSlice(nicknames, func(input_item any) (any, error) {
return input_item.(string), nil
})
anys := a.([]any)
strings := make([]string, len(anys))
for ix, a := range anys {
strings[ix] = a.(string)
}
This is cumbersome, insofar as CollectSlice() returns any, which then has to be subject to a (single-value) type assertion. This in addition to the (single-value) type assertion in the given callback function.
What is required instead is a generic function CollectSliceIntoString():
func CollectSliceIntoStringSlice[T](input_slice []T, func(input_item T*) (string, error)) ([]string, error)
that can then be used without any type assertions in a single-line, as in:
strings := CollectSliceIntoString[Nickname](nicknames, func(input_item Nickname*) (string, error) {
return string(*input_item), nil
})
The purpose here is to have a concrete type returned, to simplify (and strengthen) client code.
Consider a custom type
Nickname:Given an array of nicknames:
to obtain a slice of
string, one must useCollectSlice()as follows:This is cumbersome, insofar as
CollectSlice()returnsany, which then has to be subject to a (single-value) type assertion. This in addition to the (single-value) type assertion in the given callback function.What is required instead is a generic function
CollectSliceIntoString():that can then be used without any type assertions in a single-line, as in: