Golang泛型不包括切片或数组类型。

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

Golang Generics exclude slice or array types

问题

我有一个在Go中使用泛型的函数,不应该应用于切片或数组。但是我不知道如何做到这一点。我找到了一些示例,但只有TypeScript的示例,对我没有帮助。所以,作为一个例子,我想要像这样的东西:

func sth[T 除了切片或数组之外的任何类型](arg T) {
  ...做某事...
}
英文:

I have a function with a generic in Go that should not be applied to either slices or arrays. But I don't have an idea how to do this. I found examples for that, but only for Typescript which doesn't bring me further. So as an example, I'd like to have sth. like:

func sth[T anything_but_slices_or_arrays](arg T) {
...doSth...
}

答案1

得分: 1

你可以使用comparable约束来实现部分功能,因为切片类型不实现该接口:

func foo[T comparable](arg T) {
    fmt.Printf("%#v\n", arg) // 举个例子
}


func main() {
    i := []int{42}
    foo(i) // <- 编译错误:[]int类型不满足comparable约束
}

然而,数组(具有可比较类型的数组)是可以的:

func foo[T comparable](arg T) {
    fmt.Printf("%#v\n", arg) // 举个例子
}


func main() {
    i := [1]int{42}
    foo(i)

这段代码可以编译并输出:

[1]int{42}

所以,是否排除切片和数组取决于你的泛型函数是否需要这样的限制,这取决于泛型函数的具体功能。

通常来说,对泛型函数进行约束的目的是确保函数能够执行所需的操作。例如,如果函数需要比较泛型类型的参数,那么使用comparable约束是有意义的。但是,如果函数不需要任何特定的功能,那么就让它接受any类型的参数。

如果你只是不希望函数被任意类型的值(或某些类型的值)使用,即使从函数的功能角度来看这样做没有问题,那么可能更好的做法是通过其他方式进行监管和管理(例如代码审查、拉取请求等)。

不知道你的泛型函数具体要做什么,所以很难给出确切的答案。 Golang泛型不包括切片或数组类型。

英文:

You can get halfway there with the comparable constraint, as slices do not implement this interface:

func foo[T comparable](arg T) {
    fmt.Printf(&quot;%#v\n&quot;, arg) // for example
}


func main() {
    i := []int{42}
    foo(i) // &lt;- compiler error: []int does not satisfy comparable
}

However, arrays (of comparable types) are:

func foo[T comparable](arg T) {
    fmt.Printf(&quot;%#v\n&quot;, arg) // for example
}


func main() {
    i := [1]int{42}
    foo(i)

will compile and run to produce the output:

[1]int{42}

So it perhaps comes down to how important it is to exclude slices and arrays in your function, and that will come down to what your generic function does.

It is perhaps more common to constrain a generic function only to the extent that is needed to ensure the function can perform the operations it wishes. i.e. if the function needs to be able to compare args of a generic type, then a comparable constraint makes sense, but if a function doesn't need any specific capabilities, then let it accept any.

If you simply don't want the function used with values of some type (or types) arbitrarily, even though there is nothing wrong with doing so in terms of what the function does, then this might be better policed and regulated by other means (code review, pull requests etc.).

It's hard to say for sure without knowing exactly what your generic function is going to do. Golang泛型不包括切片或数组类型。

huangapple
  • 本文由 发表于 2023年4月4日 15:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926468.html
匿名

发表评论

匿名网友

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

确定