如何检查界面是否为golang中的map [string] string

编程入门 行业动态 更新时间:2024-10-11 17:25:30
本文介绍了如何检查界面是否为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

本文发布于:2023-11-25 10:28:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:界面   golang   string   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!