首页 > 解决方案 > golang 为切片切片(二维切片)中的现有元素赋值

问题描述

我有一个切片,它由字符串类型的切片组成。我希望能够为这片切片的各个元素赋值,不一定按顺序。然后,稍后,我希望能够更改任何特定元素的值。我已经阅读了有关切片的相同问题的帖子,但我不知道如何将其应用于切片。考虑这段代码:

package main

import (
    "fmt"
    "strconv"
)

type aRow []string
type 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)"

我错过了什么?

标签: go2dslice

解决方案


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
}

推荐阅读