英文:
range keyword and 2d slices in Go
问题
我第一次尝试使用Go语言。在过去的一个小时里,我一直不知道为什么这段代码不起作用。
grid := make([][]string, 2)
for _, row := range grid {
row = []string{"foo", "bar"}
}
fmt.Println(grid)
我期望它打印出类似以下的内容:
[
["foo", "bar"]
["foo", "bar"]
]
但实际上它拒绝编译,并显示row declared and not used
的错误信息。
显然,我在二维切片和range
关键字方面漏掉了一些东西。有什么想法吗?
英文:
I'm trying my hand at Go for the first time. For the last hour or so I've been at a loss as to why this code is not working.
grid := make([][]string, 2)
for _, row := range grid {
row = []string{"foo", "bar"}
}
fmt.Println(grid)
I expect it to print something like
[
["foo", "bar"]
["foo", "bar"]
]
but instead it refuses to compile with the message row declared and not used
.
Clearly I'm missing something with regards to 2d slices and the range
keyword. Any ideas?
答案1
得分: 8
row
不是对grid
中值的引用,而是切片值的副本。错误是因为你给row
赋了一个新的切片,但是这个值从未被使用。
这更可能是你想要的代码:
grid := make([][]string, 2)
for i := range grid {
grid[i] = []string{"foo", "bar"}
}
fmt.Println(grid)
这段代码创建了一个二维字符串切片grid
,然后使用循环为每个切片元素赋值为["foo", "bar"]
。最后打印输出grid
的值。
英文:
row
isn't a reference to the value in grid
, it's a copy of the slice value. The error is because you assign a new slice to row
, but that value is never used.
This is more likely what you want:
http://play.golang.org/p/86yHqw_JX-
grid := make([][]string, 2)
for i := range grid {
grid[i] = []string{"foo", "bar"}
}
fmt.Println(grid)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论