i taking "tour of go", , had question regarding exercise: slices example. can create picture iterating on each index using the [] operator, in c.
func pic(dx, dy int) [][]uint8 { pic := make([][]uint8, dy) := range pic { pic[i] = make([]uint8, dx) j := range pic[i] { pic[i][j] = uint8(1) } } return pic }
however, when try below, panic: runtime error: index out of range
error. tried adding print statements , calling pic(3, 3)
, printed out 3x3 array fine.
func pic(dx, dy int) [][]uint8 { pic := make([][]uint8, dy) _, y := range pic { y = make([]uint8, dx) _, x := range y { x = uint8(1) _ = x // x has used //fmt.print("1") } //fmt.print("\n") } return pic }
any thoughts on doing wrong?
the main problem attempt assignment. check example using code; https://play.golang.org/p/lwoe79jq70
what out of latter implementation 3x0 array, of inner arrays empty. reason because you're using range variable assignment doesn't work. if current index 0
, y != pic[0]
, pic[0]
assigned y
however, y
temporary storage, typically same address , on written on each iteration. after latter example executes, x direction arrays empty, indexing 1 causes panic.
basically should using first implementation because works fine , way typically this. take away is, when a, b := range something
b != something[a]
, it's on instance, goes out of scope @ bottom of loop , assigning not cause state change collection something
, instead must assign something[a]
if want modify something[a]
.