Generics cho phép viết function và type hoạt động với nhiều kiểu dữ liệu mà không cần lặp code, ví dụ func MapT any, U any U) []U nhận slice bất kỳ và trả về slice đã transform.
- Type parameters được khai báo trong dấu ngoặc vuông
[], kèm constraints để giới hạn kiểu được chấp nhận nhưany,comparable, hoặc custom interface constraints kiểutype Number interface { int | float64 }. - Trước Go 1.18, muốn viết hàm generic phải dùng
interface{}rồi type assertion, vừa mất type safety vừa verbose; generics giải quyết triệt để vấn đề này.
Generics let you write functions and types that work with multiple data types without code duplication.
- For example,
func MapT any, U any U) []Uaccepts a slice of any type and returns a transformed slice. - Type parameters are declared in square brackets
[]with constraints that restrict accepted types:any,comparable, or custom interface constraints liketype Number interface { int | float64 }. - Before Go 1.18, generic behavior required
interface{}with type assertions — sacrificing type safety and readability. - Generics solve this cleanly.