Home > Backend Development > Golang > How Can I Iterate Over a Union of Slices in a Go Generic Function Without a Core Type?

How Can I Iterate Over a Union of Slices in a Go Generic Function Without a Core Type?

Mary-Kate Olsen
Release: 2024-12-23 15:23:10
Original
614 people have browsed it

How Can I Iterate Over a Union of Slices in a Go Generic Function Without a Core Type?

Iterating Over a Union of Slices in a Generic Function Without a Core Type

In Go 1.18, generic functions allow us to work with types dynamically. However, encountering challenges in iterating over a slice composed of varying types requires additional considerations.

When dealing with type constraints, we must understand the concept of a core type. A core type exists when a single underlying type exists for all types in an interface or when all channels have the same element type and direction.

In the initial code example:

type NumberSlice interface {
    []int64 | []float64
}
Copy after login

The interface constraint NumberSlice does not have a core type because it comprises multiple underlying types: []int64 and []float64. This means we cannot range over slices of this interface.

To overcome this obstacle, we can modify the interface to require the base types instead:

type Number interface {
    int64 | float64
}

func add[N Number](n []N) {
    for _, v := range n {
        fmt.Println(v)
    }
}
Copy after login

This allows us to declare slices of int64 or float64 and iterate over them within the generic function.

Alternatively, we can define a more explicit interface with a core type:

type NumberSlice[N int64 | float64] interface {
    ~[]N
}

func add[S NumberSlice[N], N int64 | float64](n S) {
    for _, v := range n {
        fmt.Println(v)
    }
}
Copy after login

This approach ensures the interface has a known underlying type of []N for all types implementing NumberSlice[N].

By making these adjustments, we can successfully iterate over unions of slices within generic functions, providing increased flexibility in our code.

The above is the detailed content of How Can I Iterate Over a Union of Slices in a Go Generic Function Without a Core Type?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template