gpt4 book ai didi

types - 如何在 Go 中转换为类型别名?

转载 作者:IT老高 更新时间:2023-10-28 13:00:16 25 4
gpt4 key购买 nike

this playground snippet

相关代码:

type somethingFuncy func(int) bool

func funcy(i int) bool {
return i%2 == 0
}

var a interface{} = funcy

func main() {

_ = a.(func(int) bool) // Works

fmt.Println("Awesome -- apparently, literally specifying the func signature works.")

_ = a.(somethingFuncy) // Panics

fmt.Println("Darn -- doesn't get here. But somethingFuncy is the same signature as func(int) bool.")
}

第一个强制转换通过显式声明类型起作用。但第二个 Actor panic 。为什么?有没有一种干净的方法可以转换为更长的 func 签名?

最佳答案

tl;博士

对于类型断言(您使用),只有实际类型很重要。所以 somethingFuncy 只等于 somethingFuncy 而不是 func(int) bool

说明

首先,这与强制转换无关。 go中没有强制转换。有type assertionstype conversions .

您正在处理类型断言并假设相同的条件成立至于类型conversions。我在阅读您的问题时犯了同样的错误,但实际上行为存在巨大差异。

假设您有两种类型,例如 inttype MyInt int。这些都是可转换的,因为它们都是共享相同的底层类型(转换规则之一),所以这有效(play):

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

现在,假设 a 不是 int 类型,而是 interface{} 类型(play):

var a interface{} = int(10)
var b MyInt = MyInt(a)

编译器会告诉你:

cannot convert a (type interface {}) to type MyInt: need type assertion

所以现在我们不再进行conversions,而是assertions。我们需要这样做(play):

var a interface{} = int(10)
var b MyInt = a.(MyInt)

现在我们遇到了与您的问题相同的问题。此断言因 panic 而失败:

panic: interface conversion: interface is int, not main.MyInt

原因在 type assertions section 中有说明。规范:

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.

所以 int 必须与 MyInt 相同。 type identity的规则|声明(除其他规则外):

Two named types are identical if their type names originate in the same TypeSpec.

由于 intMyInt 有不同的声明 ( TypeSpecs ) 它们不相等并且断言失败。当您将 a 断言为 int 时,断言有效。所以你正在做的事情是不可能的。

奖金:

实际检查发生在 in this code ,它只是检查两种类型是否都是和预期的一样。

关于types - 如何在 Go 中转换为类型别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577423/

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