2010-11-26 37 views
5

轉到符合規範states如何在Go中創建一個map [[16] byte] []字符串?

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界面,返回[]byte,但其中我所有的哈希值與相同的算法做(這樣,我知道它適合於[16]byte)。我怎樣才能提供適當的接口,使得map類型將允許[]byte[16]byte或其某些包裝被用作密鑰?

目前我使用生成以下錯誤:

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

更新(2012年3月): GO1允許[16]byte爲重點類型。

回答

3

A string type表示UTF-8編碼字符串值的集合。字符串的行爲類似於字節數組。參見Go語言規範的Conversions部分中與字符串類型主題相關的轉換中字節片段的規則2和4。

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等)是一種「技巧」,可將Go和其他許多語言中的數字字符「7」轉換爲整數值7。

+0

你能解釋爲什麼會出現這種情況嗎?轉換爲可接受的魔術類型似乎是任意的。 – 2010-11-26 17:09:10

相關問題