英文:
Bracket syntax for custom struct types in Go
问题
我愿意在Go语言中创建C++ STL。有没有办法创建自定义的结构体,以实现用方括号语法进行索引访问?
假设这是我的数组类型:
type Array[T any] struct {
values []T
}
有没有办法添加方括号语法的索引访问,而不是使用Array.At()
或其他方法?
我希望能够使用Array[4]
而不是Array.At(4)
来访问索引为4的元素。
我该如何实现这个功能?
英文:
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?
答案1
得分: 2
不。截至Go 1.19版本,Go语言不支持运算符重载(你所问的是运算符重载的通用名称,[]
是你想要重载的具体运算符)。
请参阅常见问题解答:
> 关于运算符重载,它似乎更多是一种便利而不是绝对的要求。再次强调,没有它会更简单。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论