Skip to content

Add CollectSliceIntoString() to the collect family, that returns (result_slice []string, err error) #12

Description

@mwsis

The purpose here is to have a concrete type returned, to simplify (and strengthen) client code.

Consider a custom type Nickname:

type Nickname string

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
})

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions