gpt4 book ai didi

go - 我可以在 Golang 中将变量类型与 .(type) 进行比较吗?

转载 作者:IT王子 更新时间:2023-10-29 00:35:04 25 4
gpt4 key购买 nike

我对接口(interface)变量的 .(type) 语法感到很困惑。是否可以这样使用:

var a,b interface{}
// some code
if first.(type) == second.(type) {
}

或者 reflect.TypeOf() 是检查 a 和 b 的底层类型是否相同的唯一选项吗?我在上面的代码中做了什么比较?

最佳答案

someInterface.(type) 仅用于类型开关。事实上,如果您尝试运行它,您会在错误消息中看到它。

func main() {
var a, b interface{}
a = 1
b = 1

fmt.Println(a.(type) == b.(type))
}

prog.go:10: use of .(type) outside type switch

你可以做的是 a.(int) == b.(int),这实际上与 int(a) == int(b)

func main() {
var a, b interface{}
a = 1
b = 1

fmt.Println(a.(int) == b.(int))
}

true

关于go - 我可以在 Golang 中将变量类型与 .(type) 进行比较吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820469/

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