英文:
go map key by reference, comparison by dereference
问题
我需要使用大型地图,其中键是大型字符串。在Go的默认map
中,是否有一种方法可以指定比较测试,以便将键视为地址?如果没有,是否有好的库可以实现这一点?
请注意,我想要避免的是在进行地图查找时,长字符串不断地通过复制传递。
英文:
I need to use large maps with large strings as keys. Is there a way in go's default map
to specify the comparison test so that the key is treated as an address? If not, are there good libraries that implement this?
Note that what I want to prevent is long strings constantly being passed by copy whenever a map lookup is made.
答案1
得分: 2
对于字符串的特殊情况,Go语言默认会按照你的期望进行处理:字符串当前由指针/长度对表示,因此在复制字符串时不会复制字符串数据。
一般情况下,你不能指定自定义的比较(或哈希)函数。其他类型和自定义结构体按照规范中列出的规则进行处理:例如,指针是按地址进行比较,固定大小的数组是按值进行比较,而切片类型通常不可比较,因此包含切片类型的结构体不能用作映射键类型。
英文:
For the particular case of strings, Go does what you want by default: strings are currently represented by pointer/length pairs so you're not copying string data around when you copy strings.
In general, you can't specify a custom comparison (or hash) function. Other types and custom structs are treated according to rules listed in the spec: pointers are compared by address, for example, fixed-size arrays are compared by value, and slice types aren't comparable in general so struct types that include them aren't usable as map key types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论