"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can We Effectively Constrain Indexable Types in Go 1.18 Generics?

How Can We Effectively Constrain Indexable Types in Go 1.18 Generics?

Published on 2024-11-19
Browse:429

How Can We Effectively Constrain Indexable Types in Go 1.18 Generics?

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:

  • Maps: The union must contain only map types with identical key and element types. This restriction makes it impractical for generic algorithms that must handle maps with different keys and values.
  • Arrays: The length of an array is part of its type, so a union would need to specify all possible lengths. This can be cumbersome and prone to out-of-bounds errors.

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.

Latest tutorial More>

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