Generics in Go provide code reusability, allowing the creation of code that can be used with different types of data. Compared with Java and C's generics, Go's generics have lower performance overhead, but type inference is only conditional and has limited constraints.
Generics are a programming language feature that allows the creation of Codes for various types of data. Go 1.18 introduces generics, bringing huge changes to its ecosystem. This article will compare the similarities and differences between generics in Go and other language features, and provide practical examples.
Features | Go | Java | C |
---|---|---|---|
Syntax | func name[T any](t T) |
class Box<t></t> |
##template
|
Yes | No | No | |
Conditional | Yes | There are | |
Limited | Unlimited | Limited | |
Lower | Lower | Higher |
type Ordered interface { Less(a, b Ordered) bool } func Sort[T Ordered](arr []T) { for i := 0; i < len(arr)-1; i++ { for j := i + 1; j < len(arr); j++ { if arr[i].Less(arr[j]) { arr[i], arr[j] = arr[j], arr[i] } } } } type Int struct{ i int } func (a Int) Less(b Int) bool { return a.i < b.i } type String struct{ s string } func (a String) Less(b String) bool { return a.s < b.s } func main() { arr1 := []Int{{1}, {3}, {2}} arr2 := []String{"a", "c", "b"} Sort(arr1) Sort(arr2) fmt.Println(arr1) // [{1} {2} {3}] fmt.Println(arr2) // [{a} {b} {c}] }
The above is the detailed content of Comparison of generics and other language features in golang. For more information, please follow other related articles on the PHP Chinese website!