The core role of generics in Go 1.18 is to adapt multiple types through a single copy of code to reduce duplicate logic. 1. Generics allow the definition of type parameters so that functions or structures can handle different data types; 2. Typical usages such as merging SumInts and SumFloats into a Sum function; 3. Type constraints restrict available types, such as using int | float64 or any to accept any types; 4. Practical scenarios include implementations of general data structures such as stacks; 5. When using them, be careful to avoid over-dependence on any to maintain type safety. Understanding generics can help improve code reusability and maintenance.
Go generics start from scratch: simple usage and practical scenarios

After the introduction of generics in Go 1.18, many people thought it "looks useful", but they didn't know when or how to use them. In fact, the core goal of generics is to write a copy of code and adapt to multiple types . Not all places are required for generics, but using them where they are suitable can significantly reduce duplicate logic.
What is a generic? Why do you need it?
Generics are not a new concept, they have existed in languages such as Java and C#. Go's generic design is relatively concise, mainly to solve a pain point: the repetition problem of functions or structures when dealing with different types .

For example, you wrote a SumInts
function to calculate the sum of integer slices, and then wrote a SumFloats
to calculate the sum of floating-point slices. They are logically the same, but the types are different. At this time, you can use generics to merge these two functions into one.
How to define a generic function?
The key to defining a generic function is to introduce type parameters, put them after the function name, and wrap them in square brackets.

func Sum[T int | float64](nums []T) T { var total T for _, num := range nums { total = num } Return total }
This code means:
-
T
is a type parameter -
T
can beint
orfloat64
- The function can use
T
like normal types
The call method is also very intuitive:
ints := []int{1, 2, 3} fmt.Println(Sum(ints)) // Output 6 floats := []float64{1.5, 2.5, 3.0} fmt.Println(Sum(floats)) // Output 7
Note: Go does not support automatic type derivation to all cases, sometimes you may need to explicitly specify type parameters, such as Sum[int](...)
.
Type constraints and the use of any
In Go generics, we use "type constraints" to limit the types that are allowed to be passed in. For example, the previous example uses int | float64
, which means that only these two types are accepted.
If you want the function to accept any type, you can use any
(actually the alias for interface{}
):
func PrintAll[T any](items []T) { for _, item := range items { fmt.Println(item) } }
This function can print any type of slice content.
But be careful that once you use any
, you lose control of the specific type, and you cannot do addition, subtraction, multiplication and division operations. It is recommended only when specific behavior is not required.
Example of practical scenarios: general data structure
One of the most common uses of generics is to build common data structures. For example, you can write a general stack structure:
type Stack[T any] struct { Items []T } func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) } func (s *Stack[T]) Pop() T { if len(s.items) == 0 { var zero T return zero } last := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return last }
Then you can use:
s := Stack[int]{} s.Push(1) s.Push(2) fmt.Println(s.Pop()) // Output 2
The advantage of this writing is that it does not require the logic to be implemented separately for each type.
Basically that's it. Generics are not master keys, but it does solve the problem of duplicate code. It may be a bit tangled when you first contact, especially the type constraint piece. It is recommended to start with simple examples, such as generic functions, and then gradually try generic structures and interfaces. As long as you understand how type parameters work, many problems can be solved easily.
The above is the detailed content of Go generics tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

In Go, an interface is a type that defines behavior without specifying implementation. An interface consists of method signatures, and any type that implements these methods automatically satisfy the interface. For example, if you define a Speaker interface that contains the Speak() method, all types that implement the method can be considered Speaker. Interfaces are suitable for writing common functions, abstract implementation details, and using mock objects in testing. Defining an interface uses the interface keyword and lists method signatures, without explicitly declaring the type to implement the interface. Common use cases include logs, formatting, abstractions of different databases or services, and notification systems. For example, both Dog and Robot types can implement Speak methods and pass them to the same Anno

TheGoiopackageprovidesinterfaceslikeReaderandWritertohandleI/Ooperationsuniformlyacrosssources.1.io.Reader'sReadmethodenablesreadingfromvarioussourcessuchasfilesorHTTPresponses.2.io.Writer'sWritemethodfacilitateswritingtodestinationslikestandardoutpu

Go's time package provides functions for processing time and duration, including obtaining the current time, formatting date, calculating time difference, processing time zone, scheduling and sleeping operations. To get the current time, use time.Now() to get the Time structure, and you can extract specific time information through Year(), Month(), Day() and other methods; use Format("2006-01-0215:04:05") to format the time string; when calculating the time difference, use Sub() or Since() to obtain the Duration object, and then convert it into the corresponding unit through Seconds(), Minutes(), and Hours();

InGo,ifstatementsexecutecodebasedonconditions.1.Basicstructurerunsablockifaconditionistrue,e.g.,ifx>10{...}.2.Elseclausehandlesfalseconditions,e.g.,else{...}.3.Elseifchainsmultipleconditions,e.g.,elseifx==10{...}.4.Variableinitializationinsideif,l

Gohandlesconcurrencyusinggoroutinesandchannels.1.GoroutinesarelightweightfunctionsmanagedbytheGoruntime,enablingthousandstorunconcurrentlywithminimalresourceuse.2.Channelsprovidesafecommunicationbetweengoroutines,allowingvaluestobesentandreceivedinas

A switch statement in Go is a control flow tool that executes different code blocks based on the value of a variable or expression. 1. Switch executes corresponding logic by matching cases, and does not support the default fall-through; 2. The conditions can be omitted and Boolean expressions are used as case judgment; 3. A case can contain multiple values, separated by commas; 4. Support type judgment (typeswitch), which is used to dynamically check the underlying types of interface variables. This makes switch easier and more efficient than long chain if-else when dealing with multi-condition branches, value grouping and type checking.

Use bit operators to operate specific bits of integers in Go language, suitable for processing flag bits, underlying data, or optimization operations. 1. Use & (bit-wise) to check whether a specific bit is set; 2. Use
