map - 如何在 Go 中创建 map[[16]byte][]string?

标签 map go

Go 规范 states :

The comparison operators == and != (§Comparison operators) must be fully defined for operands of the key type; thus the key type must not be a struct, array or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.

我希望创建一个来自 Hash 的哈希值映射接口(interface),它返回 []byte,但我的所有哈希都是使用相同的算法完成的(因此我知道它适合 [16]byte)。我怎样才能提供适当的接口(interface),以便 map 类型将允许使用 []byte[16]byte 或其某些包装器作为 key ?

目前我的使用产生以下错误:

dupes := make(map[[16]byte][]string)
finddups.go:55: invalid map key type [16]uint8

更新(2012 年 3 月):Go1 允许 [16]byte 作为 key 类型。

最佳答案

A string type表示一组 UTF-8 编码的字符串值。字符串的行为类似于字节数组。请参阅 Conversions 中与字符串类型之间的转换主题中字节 slice 的规则 2 和 4。 Go 语言规范部分。

package main

import "fmt"

func main() {
    dupes := make(map[string][]string)

    hash := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    dupes[string(hash)] = []string{"a", "b"}
    hash[len(hash)-1]++
    dupes[string(hash)] = []string{"b", "c"}

    fmt.Println("len:", len(dupes))
    for k, v := range dupes {
        fmt.Println("key:", []byte(k), "value:", v)
    }
}

输出:

len: 2
key: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16] value: [b c]
key: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] value: [a b]

注意:此算法仅利用 The Go Language Specification 中给出的字符串类型和转换规则,所有实现都必须满足。这是一个“技巧”,就像 var i int = '7' - '0'(对于 ASCII、EBCDIC、Unicode 等)是一个将数字字符“7”转换为“技巧”一样到整数值 7,在 Go 和许多其他语言中。

关于map - 如何在 Go 中创建 map[[16]byte][]string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4286615/

相关文章:

map - 方法链 vs |> 管道操作符

mysql - sql.Result.LastInsertId() 的线程安全

go - 错误: Type is redeclared in this package

xml - Go 中的通用 XML 解析器

bash - 从字符串拆分数组在bash中不起作用

Go:用template.ParseFiles解析xml文件后,第一个 "<"变成 "&lt;"

具有多个参数的 CouchDB 中的 Map/Reduce?

c++ - 这些有什么区别?

java - 将 map 用于图形

不同类的 C++ Map<>.find() 重载