Ad space (banner)
๐ŸนGo Lessons
Lesson 51 / 68

Writing Generic Functions

In this lesson you will learn how to write generic functions in Go, so one function can work with several types. This is for anyone searching for "Go generics how to use".

Go 1.18 and later support generics. A type parameter [T ...] lets you write a function that works with any type instead of committing to one.

The sample code defines the type-constraint interface Ordered and uses larger[T Ordered](a, b T) T to compare both the numeric larger(3, 7) and the string larger("apple", "banana") through the same function.

A common stumbling block for beginners is what a type constraint is for. Defining a constraint interface yourself gives you fine control over which types are accepted; with a bare T and no constraint, there is no guarantee that comparison operators are available.

In real-world development it is a relatively new feature, but it is already used in standard-library packages such as slices and will only become more common.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)