dozan0001 2010-11-26 15:41
浏览 118
已采纳

如何在Go中创建地图[[16] byte] []字符串?

The Go spec 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.

I wish to create a map of hash values which come from the Hash interface, which returns []byte, but for which all my hashes are done with the same algorithm (thereby I know that it would fit into [16]byte). How can I provide the appropriate interface such that the map type will allow []byte or [16]byte or some wrapper thereof to be used as a key?

Presently my use generates the following error:

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

Update (Mar 2012): Go1 allows [16]byte as key type.

  • 写回答

1条回答 默认 最新

  • duanju9104 2010-11-26 16:29
    关注

    A string type represents the set of UTF-8 encoded string values. Strings behave like arrays of bytes. See rules 2 and 4 for byte slices in the Conversions to and from a string type topic in the Conversions section of The Go Language Specification.

    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)
        }
    }
    

    Output:

    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]
    

    Note: This algorithm merely takes advantage of the rules for string types and conversions given in The Go Language Specification, which all implementations must satisfy. It's a "trick", just like var i int = '7' - '0' (for ASCII, EBCDIC, Unicode, etc.) is a "trick" to convert a numeric character '7' to an integer value 7, in Go and many other languages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog