我覺得有點傻,因為這應該很容易,但是我只是從go開始,無法弄清楚。package mainimport "fmt"type Question struct { q []string a []string}func (item *Question) Add(q string, a string) { n := len(item.q) item.q[n] := q item.a[n] := a}func main() { var q Question q.Add("A?", "B.")}編譯時會出現錯誤:q.go:11:12:錯誤:預期為';' 或'}'或換行符q.go:12:12:錯誤:預期為';' 或'}'或換行符指的是item.q [n]的開頭大括號:= q和下一行。我敢肯定我使用的分片不正確,因為它可以與一個簡單的字符串一起正常工作,但是我不確定如何解決它。編輯:我已經按照Pat Notz的建議使用StringVectors重新實現了它,并且效果很好。以下是工作代碼:package mainimport ( fmt "fmt" vector "container/vector")type Question struct { q vector.StringVector a vector.StringVector}func (item *Question) Add(q string, a string) { item.q.Push(q) item.a.Push(a)}func (item *Question) Print(index int) { if index >= item.q.Len() { return } fmt.Printf("Question: %s\nAnswer: %s\n", item.q.At(index), item.a.At(index))}func main() { var q Question q.Add("A?", "B.") q.Print(0)}
3 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
切片只是數組的視圖,而不是實際的數組。根據您的代碼片段,我認為您想StringVector
從container/vector
軟件包中使用它。這實際上是動態調整大小的數組的唯一選擇。內置數組的大小固定。如果您事先知道要存儲多少個元素,它們也可以正常工作。

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
您不應該使用:=
中的item.q[n] := q
。
:=
僅在必須分配給新變量時使用。
在這種情況下,您只需要使用 item.q[n] = q
使用切片而不是容器/向量也是更好的選擇。go(1.0.3)不再支持vector。
將項目附加到切片的更好方法是
slice = append(slice, new_item_1,item_2,item_3)
- 3 回答
- 0 關注
- 260 瀏覽
添加回答
舉報
0/150
提交
取消