【发布时间】:2021-04-24 00:08:26
【问题描述】:
我想使用可变长度的字节数组作为映射中的键。
myMap := make(map[[]byte]int)
由于切片和变长字节数组在 go 中不是有效的键类型,所以上面的代码是无效的。
然后我读到字符串只是一组 8 位字节,通常但不一定代表 UTF-8 编码的文本。
使用这种非 UTF-8 编码的字符串作为映射键是否存在任何问题?
以下代码演示了我如何将 []byte 转换为 string 并再次转换回 []byte:
package main
import (
"bytes"
"fmt"
)
func main() {
// src is a byte array with all available byte values
src := make([]byte, 256)
for i := 0; i < len(src); i++ {
src[i] = byte(i)
}
fmt.Println("src:", src)
// convert byte array to string for key usage within a map
mapKey := string(src[:]) // <- can this be used for key in map[string]int?
//fmt.Println(mapKey) // <- this destroys the print function!
fmt.Printf("len(mapKey): %d\n", len(mapKey)) // <- that actually works
// convert string back to dst for binary usage
dst := []byte(mapKey)
fmt.Println("dst:", dst)
if bytes.Compare(src, dst) != 0 {
panic("Ups... something went wrong!")
}
}
【问题讨论】:
-
“使用这种非 UTF-8 编码的字符串作为关于哈希的映射键有什么问题吗?”你试过吗?如果是这样,您是否遇到任何问题?
标签: arrays string dictionary go