type M map[string]interface{} g-6ren">
gpt4 book ai didi

go - map[string]interface{} 的类型嵌套映射返回 "type interface {} does not support indexing"

转载 作者:数据小太阳 更新时间:2023-10-29 03:34:45 28 4
gpt4 key购买 nike

我在使用类型嵌套 map 时遇到了一个非常奇怪的问题。

gore version 0.2.6  :help for help
gore> type M map[string]interface{}
gore> m := M{"d": M{}}
main.M{"d":main.M{}}
gore> m["d"]["test"] = "will fail"
# command-line-arguments
/tmp/288178778/gore_session.go:13:8: invalid operation: m["d"]["test"] (type interface {} does not support indexing)
/tmp/288178778/gore_session.go:14:17: invalid operation: m["d"]["test"] (type interface {} does not support indexing)
error: exit status 2
exit status 2
gore> m["e"] = "this works"
"this works"
gore> m
main.M{"d":main.M{}, "e":"this works"}

我做错了什么?为什么仅仅因为 map 嵌套在 map 中就突然失败了?

最佳答案

让我们看看这个:

foo:=map[string]interface{}{}

当您定义 map[string]interface{} 时,您可以设置任何您想要的类型(任何满足 empty interface interface{} 契约 a.k.a任何类型)对于给定的字符串索引。

foo["bar"]="baz"
foo["baz"]=1234
foo["foobar"]=&SomeType{}

但是当您尝试访问某些键时,您不会得到一些 int、字符串或任何自定义结构,您会得到一个接口(interface){}

var bar string = foo["bar"] // error

为了将bar 视为一个字符串,您可以创建一个type assertion。或 type switch .

这里我们进行类型断言(live example):

if bar,ok := foo["bar"].(string); ok {
fmt.Println(bar)
}

但正如@Volker 所说,作为初学者,参加tour of go 是个好主意。以更加熟悉这些概念。

关于go - map[string]interface{} 的类型嵌套映射返回 "type interface {} does not support indexing",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413097/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com