gpt4 book ai didi

go - 为什么我在 golang 的类型断言上得到奇怪的结果?

转载 作者:行者123 更新时间:2023-12-01 22:42:34 27 4
gpt4 key购买 nike

此代码工作正常,但是,当我在一种情况下绑定(bind)它们时,例如:

var i interface{}
s := make([]map[string]interface{}, 5, 5)
i = s
switch x := i.(type) {
case []interface{}:
fmt.Println("type is an array")
fmt.Println("length is: ")
fmt.Println(len(x))
case []map[string]interface{}:
fmt.Println("type is an array")
fmt.Println("length is: ")
fmt.Println(len(x))
}
但是当我在一个case语句中绑定(bind)它们时不起作用
switch x := i.(type) {
case []interface{}, []map[string]interface{}:
fmt.Println("type is an array")
fmt.Println("length is: ")
fmt.Println(len(x))
}

最佳答案

请参阅语言规范:

The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the end of the TypeSwitchCase in the implicit block of each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.



另外,请记住 Go 是静态类型的。您无法决定在运行时声明的变量的类型。因此,如果您列出多种类型,它只是使用与开关变量相同的类型来声明变量。

关于go - 为什么我在 golang 的类型断言上得到奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607454/

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