Generics in Go enable type-safe, reusable functions and data structures. Introduced in Go 1.18, they reduce code duplication by allowing functions like func Max[T comparable](a, b T) T to work across multiple types while enforcing constraints. Type parameters in square brackets, such as [T comparable], define the acceptable operations, where comparable ensures support for comparison. Custom constraints using interfaces, like type Number interface { int | float64 | float32 }, restrict types to those supporting specific operations, such as addition in Sum[T Number](a, b T) T. Generic data structures, such as type Stack[T any] struct { items []T }, allow creation of flexible containers that work with any type, enhancing reusability without sacrificing performance or safety.
Generics in Go allow you to write functions and data structures that work with different types while maintaining type safety. Introduced in Go 1.18, they help reduce code duplication when the logic is the same across multiple types.
Define Generic Functions
To create a generic function, use type parameters inside square brackets [ ] before the regular function parameters.
For example, here’s a simple function that returns the larger of two values:
func Max[T comparable](a, b T) T {???if a > b {
??????return a
???}
???return b
}
The T is a type parameter, and comparable is a constraint that ensures T supports comparison operations like >. When calling this function, you can pass in types like int, float64, or string.
Use Type Constraints
Constraints define what operations a type parameter must support. You can use built-in constraints like comparable or any (which allows any type), or define your own using interfaces.
Example with a custom constraint:
type Number interface {???int | float64 | float32
}
func Sum[T Number](a, b T) T {
???return a b
}
This restricts T to only numeric types, ensuring the operation is valid.
Create Generic Data Structures
You can also define generic types, such as containers:
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, bool) {
???if len(s.items) == 0 {
??????var zero T
??????return zero, false
???}
???item := s.items[len(s.items)-1]
???s.items = s.items[:len(s.items)-1]
???return item, true
}
This Stack[T] works with any type, like Stack[int] or Stack[string].
Using generics makes your Go code more reusable and safer without sacrificing performance. Just keep constraints clear and limit complexity to maintain readability.
Basically just add type parameters where needed and specify what those types should support.
The above is the detailed content of How to use generics in Golang. 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.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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)

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

GracefulshutdownsinGoapplicationsareessentialforreliability,achievedbyinterceptingOSsignalslikeSIGINTandSIGTERMusingtheos/signalpackagetoinitiateshutdownprocedures,thenstoppingHTTPserversgracefullywithhttp.Server’sShutdown()methodtoallowactiverequest

MiddlewareinGowebserversarefunctionsthatinterceptHTTPrequestsbeforetheyreachthehandler,enablingreusablecross-cuttingfunctionality;theyworkbywrappinghandlerstoaddpre-andpost-processinglogicsuchaslogging,authentication,CORS,orerrorrecovery,andcanbechai

CGOenablesGotocallCcode,allowingintegrationwithClibrarieslikeOpenSSL,accesstolow-levelsystemAPIs,andperformanceoptimization;itrequiresimporting"C"withCheadersincomments,usesC.function()syntax,anddemandscarefulmemorymanagement.However,CGOinc

Implements JSON serialization and deserialization of customizable Go structures for MarshalJSON and UnmarshalJSON, suitable for handling non-standard formats or compatible with old data. 2. Control the output structure through MarshalJSON, such as converting field formats; 3. Parsing special format data through UnmarshalJSON, such as custom dates; 4. Pay attention to avoid infinite loops caused by recursive calls, and use type alias to bypass custom methods.

TheflagpackageinGoparsescommand-lineargumentsbydefiningflagslikestring,int,orboolusingflag.StringVar,flag.IntVar,etc.,suchasflag.StringVar(&host,"host","localhost","serveraddress");afterdeclaringflags,callflag.Parse(

GenericsinGoenabletype-safe,reusablefunctionsanddatastructures.IntroducedinGo1.18,theyreducecodeduplicationbyallowingfunctionslikefuncMax[Tcomparable](a,bT)Ttoworkacrossmultipletypeswhileenforcingconstraints.Typeparametersinsquarebrackets,suchas[Tcom
