How to check interface is a map[string]string in golang

三世轮回 提交于 2020-01-23 11:39:54

问题


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.

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
}

回答1:


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


来源:https://stackoverflow.com/questions/40384879/how-to-check-interface-is-a-mapstringstring-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!