lo icon indicating copy to clipboard operation
lo copied to clipboard

Add support for optional chaining

Open samber opened this issue 2 years ago • 1 comments

Some languages like Typescript or Swift offer a very cool syntactic sugar a?.b?.c?.d?.e.

In Go, we need to write a condition similar to: a != nil && a.b != nil && a.b.c != nil.

I create this issue for discussing a new helper.

In PR #106, I suggest an implementation called Safe:

type a struct {
	foo *string
}
type b struct {
	a *a
}
type c struct {
	b *b
}

v := &c{
	b: &b{
		a: nil,
	},
}

foo, ok := lo.Safe(func() string { return *v.b.a.foo })
// "", false

Calling *v.b.a.foo will panic, but this nil pointer error will be caught by lo.Safe. Other exception won't be caught.

This implementation is much more "typesafe" than something like lo.Safe(a, ".b.c.d")

WDYT?

samber avatar Apr 22 '22 16:04 samber

Safe is very good function. But can we implement real optional chaining without modifing Go Compiler? I mean, if a.b.c panics because a.b is nil, the 'Optional Chaining Function' should returns a. But how can we get information of a?

wirekang avatar Apr 22 '22 17:04 wirekang

This looks nice. It's verbose, but without a language update it looks like that's the best option. I was thinking, it might be helpful to also have a function with a default value in case of panic like func SafeOr[T any](cb func() T, fallback T) T WDYT?

CorentinClabaut avatar Dec 09 '22 10:12 CorentinClabaut

Catching out of bounds error would make sense too

renom avatar Feb 20 '23 14:02 renom