2011-08-12 26 views
3

在下面的代碼片段中,我做錯了什麼?分配到golang地圖

type Element interface{} 

func buncode(in *os.File) (e Element) { 
    <snip> 
    e = make(map[string]interface{}) 
    for { 
     var k string = buncode(in).(string) 
     v := buncode(in) 
     e[k] = v 
    } 
    <snip> 
} 

編譯給了我這個錯誤:

gopirate.go:38: invalid operation: e[k] (index of type Element) 

雙母羊牛逼EFF?

回答

2

buncode函數中聲明e Element,其中type e Element interface{}。變量e是一個標量值,您試圖對其進行索引。

Types

The static type (or just type) of a variable is the type defined by its declaration. Variables of interface type also have a distinct dynamic type, which is the actual type of the value stored in the variable at run-time. The dynamic type may vary during execution but is always assignable to the static type of the interface variable. For non-interface types, the dynamic type is always the static type.

靜態類型的eElement,標量。動態類型emap[string]interface{}

下面是您的代碼的修訂版,可編譯版本。

type Element interface{} 

func buncode(in *os.File) (e Element) { 
    m := make(map[string]interface{}) 
    for { 
     var k string = buncode(in).(string) 
     v := buncode(in) 
     m[k] = v 
    } 
    return m 
} 

你爲什麼要遞歸調用buncode

+0

但我把它的類型設置爲make的賦值?我從[類型斷言](http://golang.org/doc/go_spec.html#Type_assertions)的規範中收集了這個類型現在是我分配給它的「更大」類型的類型。 –

+0

遞歸調用獲取m的嵌套值。如果你有興趣,並有一些地道的建議,請看看這裏:http://code.google.com/p/erutor/source/browse/bencoding.py –

+0

@Matt(1) - The編譯器不會跟蹤接口{}值的動態類型,即使它可以靜態知道。您必須使用正確類型的單獨變量。 – SteveMcQwark