Home > OS >  Bracket syntax for custom struct types in Go
Bracket syntax for custom struct types in Go

Time:01-30

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).

How do I achieve this?

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related