为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
守着星空守着你 2022-11-23 19:53:56
我们不能对泛型变量使用类型断言。考虑到它是 允许的interface{},但不是受interface{}. 想知道是否有任何解决方法?// This worksfunc 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;}
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

博士

您只能对接口值执行类型断言。所以你必须首先转换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)称为类型断言。


同样来自关于为什么需要在编译时解析参数类型的泛型教程:


虽然类型参数的约束通常表示一组类型,但在编译时类型参数代表单个类型——调用代码作为类型参数提供的类型。如果类型参数的约束不允许类型参数的类型,则代码将无法编译。


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信