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

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

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

问题

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

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

抱歉我的英语不好。

  1. import (
  2. "fmt"
  3. "reflect"
  4. )
  5. func Decode(filename string, output interface{}) error {
  6. rv := reflect.ValueOf(output)
  7. if rv.Kind() != reflect.Ptr {
  8. return fmt.Errorf("输出应该是一个指向map的指针")
  9. }
  10. if rv.IsNil() {
  11. return fmt.Errorf("输出为空")
  12. }
  13. fmt.Println(reflect.TypeOf(output).Kind())
  14. return nil
  15. }
英文:

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

  1. import (
  2. "fmt"
  3. "reflect"
  4. )
  5. func Decode(filename string, output interface{}) error {
  6. rv := reflect.ValueOf(output)
  7. if rv.Kind() != reflect.Ptr {
  8. return fmt.Errorf("Output should be a pointer of a map")
  9. }
  10. if rv.IsNil() {
  11. return fmt.Errorf("Output in NIL")
  12. }
  13. fmt.Println(reflect.TypeOf(output).Kind())
  14. return nil
  15. }

答案1

得分: 26

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

  1. unboxed, ok := output.(*map[string]string)
  2. if !ok {
  3. return fmt.Errorf("Output should be a pointer of a map")
  4. }
  5. if unboxed == nil {
  6. return fmt.Errorf("Output is NIL")
  7. }
  8. // 如果程序执行到这里,unboxed 就是一个 *map[string]string 类型且不为 nil
英文:

You don't have to use reflect at all for this. A simple type assert will suffice;

  1. unboxed, ok := output.(*map[string]string)
  2. if !ok {
  3. return fmt.Errorf("Output should be a pointer of a map")
  4. }
  5. if unboxed == nil {
  6. return fmt.Errorf("Output in NIL")
  7. }
  8. // 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:

确定