gpt4 book ai didi

go - 创建二维 slice 时出错

转载 作者:数据小太阳 更新时间:2023-10-29 03:34:44 26 4
gpt4 key购买 nike

我正在尝试在 Go 中创建和初始化 2D slice 。虽然以下功能可以正常工作:

func working2D() [][]uint8 {
p := make([][]uint8, 2)
for i:=range p{
p[i]=make([]uint8, 8)
for j:=range p[i]{
p[i][j]=uint8(j)
}
}
fmt.Println(p)
return p
}

Output: [[0 1 2 3 4 5 6 7] [0 1 2 3 4 5 6 7]]

但下面的函数甚至不编译并抛出编译错误:

sample/main/range.go:35:9: v2 declared and not used

func notWorking2D() [][]uint8 {
p := make([][]uint8, 1)
for _,v := range p {
v = make([]uint8, 8)
for j, v2 := range v {
v2 = uint8(j)
}
}
fmt.Println(p)
return p
}

Output: [[],[]]

我在第二个函数中缺少什么?

最佳答案

正如安迪在评论中所说:

The second variable in a range gets set to each value in the slice as the loop iterates. Assigning to that variable does not affect the slice.

你可能只想做:

func notWorking2D() [][]uint8 {
p := make([][]uint8, 2)
for i, _ := range p {
p[i] = make([]uint8, 8)
for j, _ := range p[i] {
p[i][j] = uint8(j)
}
}
return p
}

https://play.golang.org/p/cHQc9ReJBE

关于go - 创建二维 slice 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com