无法推断 T,泛型多个类型。

huangapple go评论121阅读模式
英文:

Cannot infer T , generics multiple types

问题

func CreateSlice[T int | string](length int) []T {
	return make([]T, length)
}

我想学习go并尝试使用slicesgenerics。上面的代码中,我想表达T可以是intstring,即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)

huangapple
  • 本文由 发表于 2022年7月17日 05:50:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/73007865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定