为了账号安全,请及时绑定邮箱和手机立即绑定

golang 为切片切片(二维切片)中的现有元素赋值

golang 为切片切片(二维切片)中的现有元素赋值

Go
海绵宝宝撒 2022-06-01 12:26:33
我有一个切片,它由字符串类型的切片组成。我希望能够为这片切片的各个元素赋值,不一定按顺序。然后,稍后,我希望能够更改任何特定元素的值。我已经阅读了有关切片的相同问题的帖子,但我不知道如何将其应用于切片。考虑这段代码: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

}


查看完整回答
反对 回复 2022-06-01
  • 1 回答
  • 0 关注
  • 228 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号