Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for optional chaining #107

Open
samber opened this issue Apr 22, 2022 · 3 comments
Open

Add support for optional chaining #107

samber opened this issue Apr 22, 2022 · 3 comments

Comments

@samber
Copy link
Owner

samber commented Apr 22, 2022

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?

@wirekang
Copy link
Contributor

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?

@CorentinClabaut
Copy link
Contributor

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?

@renom
Copy link

renom commented Feb 20, 2023

Catching out of bounds error would make sense too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants