Home
Go
Generic Func Example
Updated Dec 27, 2024
Dot Net Perls
Generic. It is possible in Go to build a function that works on many different argument types—without duplicating any code. This is a generic function.
With type constraints, we can specify what types a generic function can receive. The types can be used within the function, during computations, as well.
iter.Seq
Example. Here we introduce a function that sums up the values in a slice that are below the value 10. With generics, we support many numeric types like int, uint, and int64.
Part 1 The SumValuesLessThan10 function has a type parameter T that can be an int, uint, int64, or uint8.
Part 2 In the function, we use a for-loop to see which elements are below the value 10, and then add them up.
for
Part 3 To test our generic func, we create 4 different slices of the supported element types, and pass them to SumValuesLessThan10.
package main import ( "fmt" ) // Part 1: specify generic method with T type that has 4 possible underlying types. func SumValuesLessThan10[T int | uint | int64 | uint8](t []T) T { // Part 2: loop over and sum up slice elements, and then return the sum. result := T(0) for _, n := range t { if n < 10 { result += n } } return result } func main() { // Part 3: create slices of varying types and call the generic method. slice := []int{4, 5, 50} fmt.Println(SumValuesLessThan10(slice)) slice2 := []uint{4, 5, 50} fmt.Println(SumValuesLessThan10(slice2)) slice3 := []int64{4, 5, 999999999999999999} fmt.Println(SumValuesLessThan10(slice3)) slice4 := []uint8{4, 5, 100} fmt.Println(SumValuesLessThan10(slice4)) }
9 9 9 9
Summary. With generics in Go, we use names like T, K, U and V to indicate generic parameters. We can constrain these parameters to certain types with an expression within the function type itself.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 27, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen