【问题标题】:Usage of non UTF-8-encoded string as map key使用非 UTF-8 编码的字符串作为映射键
【发布时间】: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


【解决方案1】:

在字符串不是有效的 UTF-8 的映射中使用 string 作为键没有问题。

The Go Blog: Strings, bytes, runes and characters in Go:

在 Go 中,字符串实际上是只读的字节片。

还有Spec: Comparison operators:

字符串值是可比较的和有序的,词法字节。

重要的是string 有哪些字节,它可能是有效的还是无效的UTF-8 序列。如果 2 个string 值具有相同的无效 UTF-8 字节序列,则它们相等,否则不相等。

测试无效和有效序列("\xff""\x00"):

m := map[string]byte{}
m["\xff"] = 1
m["\x00"] = 2
fmt.Println(m["\xff"], m["\x00"])

输出是(在Go Playground上试试):

1 2

【讨论】:

  • 感谢您准确快速的回答:)
猜你喜欢
  • 2011-06-27
  • 2014-07-03
  • 2015-02-15
  • 2011-08-09
  • 2014-01-18
  • 1970-01-01
  • 2015-07-26
  • 2011-08-27
相关资源
最近更新 更多