No, generic functions in Go only support user-defined types, pointer types, slice types, mapping types and channel types.
Does generic functions in Golang support all types?
Overview
Generic functions allow us to create functions that work with various types of data. Generics were introduced in Go 1.18, but they don't work with all types.
Restrictions
Generic functions in Go have some restrictions, including:
Supported types
Generic functions in Go support the following types:
Practical case
The following is an example showing how to use generic functions :
func max[T constraints.Ordered](a, b T) T { if a > b { return a } return b } func main() { maxInt := max(5, 10) // int 类型 maxFloat := max(3.14, 6.28) // float64 类型 }
Themax
function accepts two generic type parameters that implement theconstraints.Ordered
interface and returns the larger of the two. This interface provides theand
>
comparison operators.
Conclusion
Generic functions in Go are very useful for creating functions that work on various types of data. However, it has some limitations, such as the inability to use basic types or types without method sets.
The above is the detailed content of Do generic functions in Golang support all types?. For more information, please follow other related articles on the PHP Chinese website!