我想检查输出变量是否为map [string]字符串.输出应该是map [string]字符串,它应该是ptr.
我检查了ptr值.但我不知道如果是字符串与否,如何检查地图的关键.
对不起,我的英语不好
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
}
Run Code Online (Sandbox Code Playgroud)
eva*_*nal 13
您根本不必使用反射.一个简单的类型断言就足够了;
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3103 次 |
| 最近记录: |