range关键字和Go中的2D切片

huangapple go评论83阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年11月3日 06:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/33488126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定