如何在Golang中检查接口是否为map[string]string类型

huangapple go评论66阅读模式
英文:

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

问题

我想检查输出变量是否为map[string]string类型,并且它应该是一个指针。

我已经检查了指针的值。但是我不知道如何检查map的键是否为字符串。

抱歉我的英语不好。

import (
	"fmt"
	"reflect"
)

func Decode(filename string, output interface{}) error {
	rv := reflect.ValueOf(output)
	if rv.Kind() != reflect.Ptr {
		return fmt.Errorf("输出应该是一个指向map的指针")
	}
	if rv.IsNil() {
		return fmt.Errorf("输出为空")
	}
	fmt.Println(reflect.TypeOf(output).Kind())
	return nil
}
英文:

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

得分: 26

你不需要使用反射来完成这个任务。一个简单的类型断言就足够了:

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 is NIL")
}
// 如果程序执行到这里,unboxed 就是一个 *map[string]string 类型且不为 nil
英文:

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

huangapple
  • 本文由 发表于 2016年11月3日 00:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/40384879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定