我本來期望此代碼工作:如何在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
...但無論答案是對以前版本的圍棋,或者他們只是簡單的錯誤。 :/
有沒有關於C代碼的評論?這似乎與這個問題無關。這個例子可能來自任何語言;它只是一個'這裏是你如何在X中做到這一點,這是幹什麼的? – Doug 2013-02-11 07:53:25
是的,這有一個指向它。例如,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
似乎不必要地像'你做錯了!回答,以一個簡單的問題。 :( – Doug 2013-02-11 08:43:23