无法对类型参数值使用类型断言

Pet*_*erM 31 generics go

我们不能对泛型类型变量使用类型断言。考虑到它是 允许的interface{},但不是受 约束的泛型,这似乎是非常奇怪的行为interface{}。想知道是否有任何解决方法?

// This works
func isInt(x interface{}) bool {
    _, ok := x.(int)
    return ok;
}

// Compile Error
// invalid operation: cannot use type assertion on type parameter 
// value x (variable of type T constrained by interface{})
func isInt2[T interface{}](x T) bool {
    _, ok := x.(int)
    return ok;
}
Run Code Online (Sandbox Code Playgroud)

col*_*tor 69

太长了;博士

\n

您只能对接口值执行类型断言。因此,您必须首先转换x为有效的接口类型,any/interface{}在本例中:

\n
func isInt[T any](x T) (ok bool) {\n\n    _, ok = any(x).(int) // convert, then assert\n    return\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

那么为什么会编译失败呢?

\n
_, ok = x.(int)   // ... cannot use type assertion on type parameter value ...\n
Run Code Online (Sandbox Code Playgroud)\n

x\ 的类型T是类型参数,而不是接口。它仅受接口约束。Go(修订版1.18)语言规范明确规定类型断言中不允许使用类型参数

\n
\n

x对于接口类型的表达式,但不是类型参数和类型T...,该表示法x.(T)称为类型断言。

\n
\n
\n

还来自泛型教程,了解为什么参数类型需要在编译时解析:

\n
\n

虽然类型参数\xe2\x80\x99s 约束通常表示一组\n类型,但在编译时,类型参数代表单个类型\xe2\x80\x93\n该类型由调用代码作为类型参数提供。如果 type\ngument\xe2\x80\x99s 类型不是类型参数\xe2\x80\x99s 约束允许的\xe2\x80\x99s 类型,则代码\n将无法编译\xe2\x80\x99s。

\n
\n