From 8d6f0e39dd3cf49407817db0830e91313528b2d1 Mon Sep 17 00:00:00 2001 From: Tim Scheuermann Date: Fri, 24 Jul 2020 12:55:01 +0200 Subject: [PATCH] Added MustGet, fixed a rare panic, fixed Get comment --- uncertain.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/uncertain.go b/uncertain.go index 3dc9ba7..9b8ae8f 100644 --- a/uncertain.go +++ b/uncertain.go @@ -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: