Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bracket syntax for custom struct types in Go

I’m willing to create C++ STL in Go. Is there a way to create custom structs that implement bracket syntax for index accessing?

Assume this is my array type:

type Array[T any] struct {
    values []T
}

Is there any way I can add bracket syntax indexation instead of Array.At() or any other?
I want to be able to access f.e index 4 using Array[4] instead of Array.At(4).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do I achieve this?

>Solution :

No. As of the Go 1.19, Go does not support operator overloading (which is the general name for what you’re asking for — [] being the specific operator you want to overload).

See the FAQ:

Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading