Member-only story

Go 1.21: Comprehensive Review of Generic Functions

Beck Moulton
5 min readSep 7, 2023

--

In the Go programming language, generics have long been a highly anticipated feature. With the release of Go 1.21, this comprehensive guide aims to provide a detailed exploration of generics in Go 1.21, elucidating their advantages, syntax, implementation, and best practices.

Basic Syntax of Generics in Go 1.21:

To define generic functions or types, you can use the T keyword followed by the name of the generic type parameter enclosed in square brackets []. For example, to create a generic function that takes a slice of any type and returns its first element, you can define it like this:

func First[T any](items []T) T {
return items[0]
}

In the example above, [T any] represents the type parameter T, which stands for any type. The any keyword indicates that T can be any valid type. Then, you can call the First function with any slice type, and the function will return the first element of that slice. For example:

func func1() {
intSlice := []int{1, 2, 3, 4, 5}
firstInt := First[int](intSlice) // returns 1

println(firstInt)

stringSlice := []string{"apple", "banana", "cherry"}
firstString := First[string](stringSlice) // returns "apple"

println(firstString)
}

Note that when calling a generic function, you specify the type parameter in square brackets []. This allows the compiler to generate specific code for that type during compilation.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet