Indexing Constraints in Go 1.18 Generics
With the introduction of generics in Go 1.18, developers have the opportunity to implement algorithms that work with specific types. One common requirement is to use types that support indexing, such as arrays, slices, maps, and strings.
Indexable Constraint
To restrict a type parameter to indexable types, consider using the following constraint with a union:
type Indexable interface {
~[]byte | ~string
}
Limitations of Indexable Constraint
While the above constraint works for indexing bytes and strings, there are limitations to using it with other indexable types, such as maps and arrays:
Alternative Approach
Due to these limitations, the only practical union that supports indexing is []byte | string. This union allows for indexing operations but does not support range operations because it lacks a core type.
Example Usage
The following example demonstrates how to use the Indexable constraint:
func GetAt[T Indexable](v T, i int) byte {
return v[i]
}
This function takes an indexable value and an index and returns the byte at the specified index.
Conclusion
While Go 1.18 provides a way to constrain types to indexable types using a union, the limitations of that constraint mean that it is only practical for a limited set of use cases, namely indexing bytes and strings.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3