【问题标题】:golang Assigning a value to an existing element in a slice of slices (2d slice)golang 为切片切片(二维切片)中的现有元素赋值
【发布时间】:2020-08-10 01:37:12
【问题描述】:

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

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)"

我错过了什么?

【问题讨论】:

  • 应用程序创建一行并将其分配给所有列。通过在 for 循环中移动语句 r := make(aRow, 4) 为每一列创建新行。
  • 如果你不介意,你能不能也提供预期的输出

标签: go 2d slice


【解决方案1】:

您正在为每一列附加同一行 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
}

【讨论】:

  • 非常感谢。这填补了我理解中的一个重大空白。
猜你喜欢
  • 1970-01-01
  • 2011-05-02
  • 2021-04-14
  • 2013-03-15
  • 2021-08-18
  • 2021-01-15
  • 2013-04-12
  • 2018-01-09
  • 2021-01-12
相关资源
最近更新 更多