如何检查界面是否为golang中的map [string] string [英] How to check interface is a map[string]string in golang

查看:56
本文介绍了如何检查界面是否为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆