What are the ways to write generic code in Go?
sobes.tech AI
Answer from AI
The main ways to write generic code in Go are:
-
Interfaces: Allow writing functions that work with any types satisfying a specific set of methods.
// Defining the Reader interface type Reader interface { Read(p []byte) (n int, err error) } // Function that works with any type implementing Reader func ProcessData(r Reader) error { // reading data from Reader return nil } -
Empty interface (
interface{}): A universal type that can represent any value. Requires type assertion before use.func PrintAnything(v interface{}) { // Type assertion with check if s, ok := v.(string); ok { fmt.Println("This is a string:", s) } else if i, ok := v.(int); ok { fmt.Println("This is an integer:", i) } } -
Generics / Parameterized types (type parameters): Allow writing functions and types that work with arbitrary sets of types specified at declaration. Introduced in Go 1.18.
// Function that works with slices of any type T func PrintSlice[T any](s []T) { for _, v := range s { fmt.Println(v) } } // Generic Pair type with parameters T1 and T2 type Pair[T1, T2 any] struct { First T1 Second T2 } -
Reflection (
reflect): Allows exploring and interacting with types and values at runtime. Often used for complex scenarios but can be less performant and safe than other approaches.import "reflect" func GetTypeName(v interface{}) string { return reflect.TypeOf(v).Name() }
The choice of method depends on the specific task and the required level of flexibility and performance. Generics are the preferred way to create generic algorithms and data structures in modern Go. Interfaces remain a key mechanism for polymorphism and behavior definition. Empty interfaces and reflection are used less frequently, for more specific cases.