Introduction to Generics
Veeg om het menu te tonen
What Are Generics in Go?
Generics in Go let you write functions, types, and data structures that work with any data type. Instead of repeating similar code for different types, you define a single, flexible version using type parameters. This makes your code more reusable and easier to maintain.
Benefits of Using Generics
- Code reusability: Share the same logic across multiple types without rewriting code;
- Type safety: Catch type errors at compile time, reducing bugs;
- Cleaner APIs: Simplify your interfaces by avoiding unnecessary conversions or empty interfaces (
interface{}); - Performance: Avoid runtime type assertions, which can slow down your code.
Generics in Go allow you to write functions and types that work with different data types without duplicating code. The syntax uses type parameters in square brackets [].
main.go
12345678910111213141516package main import "fmt" // A generic function that returns the first element of a slice func First[T any](slice []T) T { return slice[0] } func main() { nums := []int{1, 2, 3} words := []string{"hello", "world"} fmt.Println(First(nums)) // 1 fmt.Println(First(words)) // hello }
-
[T any]:Tis a type parameter, and any meansTcan be any type; -
First[T any](slice []T) T: the function takes a slice of any typeTand returns an element of the same type; -
Generics let you write reusable, type-safe code without repeating logic for different types.
Generics are especially useful when building data structures like stacks, queues, or maps, and when writing utility functions that operate on different types. By using generics, you write code that is both flexible and reliable.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.