Skip to content

Commit

Permalink
Added MustGet, fixed a rare panic, fixed Get comment
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Scheuermann committed Jul 24, 2020
1 parent a336c44 commit 8d6f0e3
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions uncertain.go
Original file line number Diff line number Diff line change
@@ -9,13 +9,13 @@ import (

// Get the data nested in from when following path. You can access maps by providing the key,
// arrays, slices and strings by the index and structs by the field name. Pointers and interfaces
// are dereferenced except when they are the last item in the path.
// are always dereferenced.
func Get(from interface{}, path ...interface{}) (interface{}, error) {
v, err := get(reflect.ValueOf(from), path)
if err != nil {
return nil, err
}
if !v.IsValid() {
if !v.CanInterface() {
return nil, nil
}
return v.Interface(), nil
@@ -120,6 +120,15 @@ func get(from reflect.Value, path []interface{}) (reflect.Value, error) {
return reflect.Value{}, errors.New("can't walk the rest of the path for" + from.String())
}

// MustGet does the same as Get but panics in case of an error.
func MustGet(from interface{}, path ...interface{}) interface{} {
res, err := Get(from, path...)
if err != nil {
panic(err.Error())
}
return res
}

func anyToInt(i interface{}) (int, bool) {
switch t := i.(type) {
case string:

0 comments on commit 8d6f0e3

Please sign in to comment.