Skip to content

Commit

Permalink
Introduced a built-in deref function specifically designed to recursi…
Browse files Browse the repository at this point in the history
…vely dereference any provided value.
  • Loading branch information
ckganesan committed Jan 2, 2024
1 parent f9e1abe commit c64b181
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions builtin/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,18 +297,28 @@ func bitFunc(name string, fn func(x, y int) (any, error)) *Function {
// Deref takes an interface{} and recursively dereferences it if it's a pointer.
// If it encounters a nil pointer at any level, it returns the nil pointer itself.
func Deref(v any) any {
if v == nil {
return nil
}
val := reflect.ValueOf(v)

// Recursively dereference pointers
for val.Kind() == reflect.Ptr {
// Recursively dereference pointers and interfaces
for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
if val.IsNil() {
// If it's a nil pointer, return as is
return val.Interface()
// If it's a nil pointer or interface, return nil
return nil
}
// Safeguard against panics when interface doesn't hold a value
if !val.IsValid() {
return nil
}
// Move to the pointed value
// Move to the referenced value
val = val.Elem()
}

// Return the final (non-pointer) value
// Return the dereferenced value, or nil if invalid
if !val.IsValid() {
return nil
}
return val.Interface()
}

0 comments on commit c64b181

Please sign in to comment.