无法对类型参数进行类型断言处理
时间:2024-02-11
浏览:107
作者:佚名
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《无法对类型参数进行类型断言处理》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
问题内容
我们不能对泛型类型变量使用类型断言。考虑到 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;
}
正确答案
tl;博士
您只能对接口值执行类型断言。因此,您必须首先将 x 转换为有效的接口类型,在本例中为 any / interface{}:
func isint[t any](x t) (ok bool) {
_, ok = any(x).(int) // convert, then assert
return
}
那么为什么是fail to compile呢?
_, ok = x.(int) // ... cannot use type assertion on type parameter value ...
x 的类型 t 是类型参数,而不是接口。它仅受接口约束。 go(修订版 1.18)语言规范明确规定 type assertion 中不允许使用 type parameters:
对于接口类型但不是类型的表达式 x
参数,以及类型 t ...符号 x.(t) 称为类型断言。
另外来自 generics tutorial 关于为什么参数类型需要在编译时解析:
虽然类型参数的约束通常表示一组 类型,在编译时类型参数代表单一类型 – 调用代码作为类型参数提供的类型。如果类型 参数的类型不被类型形参的约束所允许, 代码无法编译。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
11.28
热门专题
