Home > Backend Development > Golang > How Can Generics in Go Handle Slices of Different Numeric Types?

How Can Generics in Go Handle Slices of Different Numeric Types?

DDD
Release: 2024-12-25 02:12:16
Original
395 people have browsed it

How Can Generics in Go Handle Slices of Different Numeric Types?

Using Generics with Slices of Different Types in Go

Consideration of generics in Go involves the concept of core types for interfaces. An interface constraint, such as NumberSlice, has no core type since it encompasses multiple underlying types (e.g., []int64 and []float64). This poses a hindrance when attempting to iterate over slices within a generic function.

To resolve this issue, one approach is to alter the interface to mandate the base types, leaving the slice type to be determined 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

However, an even more thorough but verbose solution involves explicitly declaring the core type within the interface constraint:

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 that the interface has a specific underlying type ([]N) and that the function can accept and process slices of either int64 or float64.

The above is the detailed content of How Can Generics in Go Handle Slices of Different Numeric Types?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template