gpt4 book ai didi

Go类型断言转换

转载 作者:IT王子 更新时间:2023-10-29 01:07:16 24 4
gpt4 key购买 nike

我可以像这样将 int 转换为 float64:

var a int = 10
var b float64 = float64(a)

关于类型断言,Effective Go 指出:“类型必须是接口(interface)持有的具体类型,或者是值可以转换为的第二个接口(interface)类型。”

考虑到这一点,为什么以下操作会失败:

func foo(a interface{}) {
fmt.Println(a.(float64))
}

func main() {
var a int = 10
foo(a)
}

这会导致 panic :接口(interface)转换:接口(interface)是 int,不是 float64

请注意 Go 规范说:

'对于接口(interface)类型的表达式x和类型T,初级表达式

x.(T)

断言 x 不是 nil 并且存储在 x 中的值是 T 类型。'

这确实与 Effective Go 声明相矛盾,但似乎更符合我所看到的。

最佳答案

This sentence在 Effective Go 中似乎确实令人困惑。看来作者当时在想结构体。

The chapter on assertions in the specification更清楚了:

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.

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

事实you can convert your int to a float (反之亦然)并不意味着您可以断言它们是同一类型。

关于Go类型断言转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16837375/

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