Open samber opened 2 years ago
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
?
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?
Catching out of bounds error would make sense too
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
:Calling
*v.b.a.foo
will panic, but this nil pointer error will be caught bylo.Safe
. Other exception won't be caught.This implementation is much more "typesafe" than something like
lo.Safe(a, ".b.c.d")
WDYT?