go - 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)"
我错过了什么?
解决方案
您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
}
推荐阅读
- java - 列映射的 log4j2 模式布局不起作用
- javascript - 如何从角度 5 的动态输入中获取价值?
- angular - 角度构建失败
- android - Facebook SDK“user_likes”权限导致“无效范围”
- mysql - 根据条件计算事件的总时间
- excel - VBA Internet Explorer 自动化错误
- spring-mvc - 使用spring mvc上传excel文件后如何解决错误的请求错误?
- linux - 如何在 RHEL Azure VM 上的 /mnt/resource 中创建目录
- .net - 在 Teamcity 上构建混合解决方案(.NET Framework 和 .NET Core)时找不到包
- javascript - 通过索引获取特定元素的文本