gpt4 book ai didi

go - 接口(interface){}类型理解

转载 作者:IT王子 更新时间:2023-10-29 01:55:51 25 4
gpt4 key购买 nike

无法理解的问题:

    var foo interface{}
foo = make(map[string]int)
fmt.Println(foo) // map[]

但是

    foo["one"] = 1

prog.go:10: 无效操作:foo["one"](接口(interface)类型索引 {})[进程以非零状态退出]

这是为什么?

最佳答案

foo 属于 interface{} 类型。它可能包含一张 map ,但它仍然是一个界面。

为了进行 map 查找,您首先需要进行类型断言:

foo.(map[string]int)["one"] = 1

有关类型断言的更多信息,请参阅 Go specifications :

For an expression x of interface type and a type T, the primary expression
x.(T)
asserts that x is not nil and that the value stored in x is of type T.
The notation x.(T) is called a type assertion.

关于go - 接口(interface){}类型理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21276759/

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