不能对类型参数值使用类型断言

我们不能对泛型变量使用类型断言。考虑到它是 允许的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;

}


守着星空守着你
浏览 88回答 1
1回答

宝慕林4294392

博士您只能对接口值执行类型断言。所以你必须首先转换x为有效的接口类型,any/interface{}在这种情况下:func isInt[T any](x T) (ok bool) {    _, ok = any(x).(int) // convert, then assert    return}那么为什么编译失败呢?_, ok = x.(int)   // ... cannot use type assertion on type parameter value ...x的类型T是类型参数,而不是接口。它仅受接口约束。Go(修订版1.18)语言规范明确指出类型参数在类型断言中是不允许的:对于接口类型的表达式x,但不是类型参数和类型T......该表示法x.(T)称为类型断言。同样来自关于为什么需要在编译时解析参数类型的泛型教程:虽然类型参数的约束通常表示一组类型,但在编译时类型参数代表单个类型——调用代码作为类型参数提供的类型。如果类型参数的约束不允许类型参数的类型,则代码将无法编译。
打开App,查看更多内容
随时随地看视频慕课网APP