lo icon indicating copy to clipboard operation
lo copied to clipboard

Proposal: add a function that returns the first of multiple return values

Open oka-tan opened this issue 2 years ago • 1 comments

In the same vein as lo.Must, add a lo.First that simply returns the first argument from a list of arguments.

Why?

Mostly so you can do

foo(lo.First(bar()))

and

foo := FooStruct{
  fooField: lo.First(bar())
}

So like a generic lo.Must that doesn't panic.

Sample implemention:

func First[T any](t T, rest ...any) T {
  return t
}

Sample usage:

func IntDiv(m, n int) (int, int) {
  return m / n, m % n
}

func main() {
  fmt.Printf("%d divided by %d is %d\n", 5, 3, lo.First(IntDiv(5, 3)))
}

oka-tan avatar Apr 27 '23 02:04 oka-tan

I'm thinking lo.First should be similar to lo.Last but returns the first element of a slice.

Maybe the functionality you're describing can be called NthResult?

noel-yap avatar Jun 13 '23 17:06 noel-yap