我有一個切片,它由字符串類型的切片組成。我希望能夠為這片切片的各個元素賦值,不一定按順序。然后,稍后,我希望能夠更改任何特定元素的值。我已經閱讀了有關切片的相同問題的帖子,但我不知道如何將其應用于切片。考慮這段代碼:package mainimport ( "fmt" "strconv")type aRow []stringtype aGrid struct { col []aRow}func main() { var c aGrid r := make(aRow, 4) // each row will have 4 elements for i := 0; i < 3; i++ { c.col = append(c.col, r) // there will be 3 rows } i, j := 1, 2 c.col[i][j] = "i=" + strconv.Itoa(i) + " j=" + strconv.Itoa(j) fmt.Println("c= ", c) // c= {[[ i=1 j=2 ] [ i=1 j=2 ] [ i=1 j=2 ]]}}我想將字符串分配給 c 的第 i 個切片的第 j 個元素,但它將字符串分配給 c 的每個切片的第 j 個元素。我試過得到內部切片的支持值,比如i, j := 1, 2 c.col[i][j].value = "i=" + strconv.Itoa(i) + " j=" + strconv.Itoa(j)// yields "c.col[i][j].value undefined (type string has no field or method value)"和指針 p := &c.col[i][j] p.value = "i=" + strconv.Itoa(i) + " j=" + strconv.Itoa(j)// yields "p.value undefined (type *string has no field or method value)"我錯過了什么?
1 回答

HUWWW
TA貢獻1874條經驗 獲得超12個贊
您r為每一列附加相同的行。
c.col = append(c.col, r)
因此,每一列都有相同的行r,為什么設置在一行中意味著設置在每一行中。
為每一列創建新行。
for i := 0; i < 3; i++ {
r := make(aRow, 4) // each row will have 4 elements
c.col = append(c.col, r) // there will be 3 rows
}
- 1 回答
- 0 關注
- 223 瀏覽
添加回答
舉報
0/150
提交
取消