本文介绍了如何检查界面是否为golang中的map [string] string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查输出变量是否为map [string] string.输出应为map [string] string且应为ptr.
I want to check the output variable is map[string]string or not. the output should be a map[string]string and it should be a ptr.
我检查了ptr值.但是我不知道如何检查map的键是否为字符串.
I checked ptr value. But I don't know how to check the key of map if is string or not.
对不起,我的英语不好
sorry for my bad english
import ( "fmt" "reflect" ) func Decode(filename string, output interface{}) error { rv := reflect.ValueOf(output) if rv.Kind() != reflect.Ptr { return fmt.Errorf("Output should be a pointer of a map") } if rv.IsNil() { return fmt.Errorf("Output in NIL") } fmt.Println(reflect.TypeOf(output).Kind()) return nil } 推荐答案您完全不必为此使用反射.一个简单的类型assert就足够了;
You don't have to use reflect at all for this. A simple type assert will suffice;
unboxed, ok := output.(*map[string]string) if !ok { return fmt.Errorf("Output should be a pointer of a map") } if unboxed == nil { return fmt.Errorf("Output in NIL") } // if I get here unboxed is a *map[string]string and is not nil更多推荐
如何检查界面是否为golang中的map [string] string
发布评论