[英]How to cast interface{} to a map in GO
I am new to Go & I am trying to learn how to cast interface{} to a Map.我是 Go 的新手,我正在尝试学习如何将 interface{} 转换为 Map。 Here is an example of what I am trying to implement.
这是我正在尝试实现的示例。
Playground link: https://play.golang.org/p/3jhKlGKO46Z游乐场链接: https://play.golang.org/p/3jhKlGKO46Z
Thanks for the help.谢谢您的帮助。
package main
import (
"fmt"
)
func main() {
Map := make(map[string]interface{})
test(Map)
for k,v := range Map {
fmt.Println("key : %v Value : %v", k, v)
}
}
func test(v interface{}) error{
data := make(map[int]interface{})
for i := 0; i < 10; i++ {
data[i] = i * 5
}
for key,val := range data {
// fmt.Println("key : %v Value : %v", key, val)
v[key] = val
}
return nil
Go supports type assertions for the interfaces. Go 支持接口的类型断言。 It provides the concrete value present in the interface.
它提供了界面中存在的具体值。
You can achieve this with following code.您可以使用以下代码实现此目的。
m, ok := v.(map[int]interface{})
if ok {
// use m
_ = m
}
If the asserted value is not of given type, ok
will be false
如果断言的值不是给定类型,则
ok
将为false
If you avoid second return value, the program will panic for wrong assertions.如果你避免第二个返回值,程序会因为错误的断言而恐慌。
I strongly recommend you to go through https://tour.golang.org我强烈推荐你到 go 到https://tour.golang.org
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.