Home > Backend Development > Golang > How to Iterate Over a Union of Slices in Go Generic Functions?

How to Iterate Over a Union of Slices in Go Generic Functions?

Linda Hamilton
Release: 2025-01-05 05:31:08
Original
260 people have browsed it

How to Iterate Over a Union of Slices in Go Generic Functions?

Iterating Over a Union of Slices in Generic Functions

Generics in Go allow functions to operate on a range of types, enabling code reuse and type safety. However, when working with slices of different element types, there may be challenges when iterating over them within generic functions.

Consider the following example that aims to sum up elements of a slice, potentially containing either integers or floats:

package main

import "fmt"

// NumberSlice constraint
type NumberSlice interface {
    []int64 | []float64
}

func add[N NumberSlice](n N) {
    // want: to range over n and print value of v
    for _, v := range n {
        fmt.Println(v)
    }
}

func main() {
    ints := []int64{1, 2}
    add(ints)
}
Copy after login

When running this code, the following error occurs:

cannot range over n (variable of type N constrained by NumberSlice) (N has no core type)
Copy after login

The issue lies in the lack of a "core type" for the NumberSlice interface constraint. A core type represents a single underlying type shared by all types in the interface's type set. Since NumberSlice encompasses both []int64 and []float64, it has no core type.

To resolve this issue, there are a few approaches:

  1. Enforce a Common Base Type:
    Modify the interface constraint to specify the base types and stipulate the slice type within the function signature:

    type Number interface {
        int64 | float64
    }
    
    func add[N Number](n []N) {
        for _, v := range n {
            fmt.Println(v)
        }
    }
    Copy after login
  2. Use Generics with Explicit Typing:
    Declare a generic slice type that specifies the element type and use explicit typing to indicate the desired element type:

    type NumberSlice[N int64 | float64] interface {
        ~[]N // indicates a core type of []N
    }
    
    func add[S NumberSlice[N], N int64 | float64](n S) {
        for _, v := range n {
            fmt.Println(v)
        }
    }
    Copy after login

By specifying a core type, the compiler can infer the appropriate iteration behavior, enabling the desired operation of iterating over the slice within the generic function.

The above is the detailed content of How to Iterate Over a Union of Slices in Go Generic Functions?. 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