英文:
Cannot infer T , generics multiple types
问题
func CreateSlice[T int | string](length int) []T {
return make([]T, length)
}
我想学习go
并尝试使用slices
和generics
。上面的代码中,我想表达T
可以是int
或string
,即T int | string
。当我创建这个函数时,编译器没有报错,但是当我调用它时,它会显示cannot infer T
。
slices.CreateSlice(10)
是否有任何限制,或者我在语法上犯了一些错误?
英文:
func CreateSlice[T int | string](length int) []T {
return make([]T, length)
}
Try to learn go
and want to play with slices
and generics
. Above you can see that I want to say T
can be or int
or string
=> T int | string
. Compiler say nothing about this case when I create this function , but on the moment I call it , it says cannot infer T
slices.CreateSlice(10)
Is there any restriction , or do I make some mistaces in syntax ?
答案1
得分: 4
编译器无法从slices.CreateSlice(10)
中确定T
,因为T
没有作为参数使用。通过显式指定T
来修复:
slices.CreateSlice[int](10) // 评估为长度为10的[]int
slices.CreateSlice[string](10) // 评估为长度为10的[]string
英文:
The compiler cannot determine T
from slices.CreateSlice(10)
because T
is not used as an argument. Fix by specifying T
explicitly:
slices.CreateSlice[int](10) // evaluates to []int with len(10)
slices.CreateSlice[string](10) // evaluates to []string with len(10)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论