2013-02-11 38 views
1

我本來期望此代碼工作:如何在Go中有一個指向它的數組的指針結構?

package main 

type Item struct { 
    Key string 
    Value string 
} 

type Blah struct { 
    Values []Item 
} 

func main() { 
    var list = [...]Item { 
    Item { 
     Key : "Hello1", 
     Value : "World1", 
    }, 
    Item { 
     Key : "Hello1", 
     Value : "World1", 
    }, 
    } 

    _ = Blah { 
    Values : &list, 
    } 
} 

我想這將是這樣做的正確方法;值是一個切片,列表是一個數組。 &列表應該是一個分片,可以分配給Item [],對不對?

...但相反,它的錯誤與消息:

cannot use &list (type *[2]Item) as type []Item in assignment 

在C語言中,你會寫:

struct Item { 
    char *key; 
    char *value; 
}; 

struct Blah { 
    struct Item *values; 
}; 

你怎麼做,在圍棋?

我看到了這樣一個問題: Using a pointer to array

...但無論答案是對以前版本的圍棋,或者他們只是簡單的錯誤。 :/

回答

4

切片不是簡單的指向數組的指針,它具有包含其長度和容量的內部表示。

如果你想從list片,你可以這樣做:

_ = Blah { 
    Values : list[:], 
} 
3

圍棋是,幸運的是,沒有那麼詳細,因爲它可能會從OP看起來。這工作:

package main 

type Item struct { 
     Key, Value string 
} 

type Blah struct { 
     Values []Item 
} 

func main() { 
     list := []Item{ 
       {"Hello1", "World1"}, 
       {"Hello2", "World2"}, 
     } 

     _ = Blah{list[:]} 
} 

(也here

PS:我建議在圍棋不寫C。

+0

有沒有關於C代碼的評論?這似乎與這個問題無關。這個例子可能來自任何語言;它只是一個'這裏是你如何在X中做到這一點,這是幹什麼的? – Doug 2013-02-11 07:53:25

+2

是的,這有一個指向它。例如,OP展示瞭如何在Go中進行編碼時輕鬆地思考C,導致對Go數組和Go切片的誤解。 Go中的'v [] T'與C中的'T [] v'不同。這不是陷入這種陷阱的唯一地方。 Go很像C,而在很多方面實際上並沒有像C那麼接近C。 PS:超過必要的詳細複合文字也是一個C-ism,IMO。 – zzzz 2013-02-11 08:15:00

+0

似乎不必要地像'你做錯了!回答,以一個簡單的問題。 :( – Doug 2013-02-11 08:43:23

2

當您剛開始使用Go時,完全忽略數組,只是使用切片是我的建議。陣列很少使用,會給初學者帶來很多麻煩。如果你有一個切片,那麼你不需要一個指向它的指針,因爲它是一個引用類型。

Here is your example帶切片,沒有指針,這是更習慣。

package main 

type Item struct { 
    Key string 
    Value string 
} 

type Blah struct { 
    Values []Item 
} 

func main() { 
    var list = []Item{ 
     Item{ 
      Key: "Hello1", 
      Value: "World1", 
     }, 
     Item{ 
      Key: "Hello1", 
      Value: "World1", 
     }, 
    } 

    _ = Blah{ 
     Values: list, 
    } 
} 
相關問題