Home  >  Article  >  Backend Development  >  Golang generics exclude slice or array types

Golang generics exclude slice or array types

WBOY
WBOYforward
2024-02-13 11:00:19684browse

Golang 泛型排除切片或数组类型

php editor Xiaoxin brings you an article about Golang generics today. Generics are a much-anticipated feature in Golang, but the latest proposal excludes support for slice or array types. This article will explain the reasons for this decision and discuss the impact on developers. Let’s take a closer look!

Question content

I have a function in Go with generics that should not be applied to slices or arrays. But I don't know how to do it. I found examples of this, but only in Typescript, which didn't get me any further. For example, I want something. picture:

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

Solution

You can usecomparable Constraint reached halfway because slice does not implement this interface:

func foo[t comparable](arg t) {
    fmt.printf("%#v\n", arg) // for example
}


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

However, arrays (similar types) are:

func foo[t comparable](arg t) {
    fmt.printf("%#v\n", arg) // for example
}


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

will compile and run to produce output:

[1]int{42}

So it may depend on the importance of excluding slices and arrays in your function, which in turn depends on what your generic function does.

A more common approach might be to limit a generic function only to the scope required to ensure that the function can do what it wants. That is, if the function requires arguments that can be compared of generic types, then the comparable constraint makes sense, but if the function does not require any specific functionality, then let it accept any.

If you just don't want to use the function with values ​​of a certain type (or types) arbitrarily, even if there is nothing wrong with doing so in terms of the functionality of the function, then this can be done through other means (code review, pull requests, etc.) to be better regulated and policed.

It's hard to determine without knowing exactly what your generic function is doing. :)

The above is the detailed content of Golang generics exclude slice or array types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Go Gin: verify base64Next article:Go Gin: verify base64