gpt4 book ai didi

arrays - 使用非UTF-8编码的字符串作为映射键

转载 作者:行者123 更新时间:2023-12-03 10:09:12 25 4
gpt4 key购买 nike

我想在 map 中使用可变长度的字节数组作为键。

myMap := make(map[[]byte]int)
由于 slice 和可变长度字节数组在go中不是有效的键类型,因此上面的代码无效。
然后,我读到字符串只是一组8位字节,通常,但是 不一定是,它表示UTF-8编码的文本。
将此类非UTF-8编码的字符串用于有关散列的映射键是否存在任何问题?
以下代码演示了如何将[] byte转换为字符串并再次转换回[] 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映射中,将string用作键是没有问题的。
The Go Blog: Strings, bytes, runes and characters in Go:

In Go, a string is in effect a read-only slice of bytes.


Spec: Comparison operators:

String values are comparable and ordered, lexically byte-wise.


重要的是 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

关于arrays - 使用非UTF-8编码的字符串作为映射键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65795784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com