I'm doing golang tutorial, and the very first exercise is giving me a headache.
The exercise in a nutshell wants me to dynamically create a array with dx*dy dimention.
This is my function that receives dx
, dy
and returns [dx][dy]uint8
array that works:
func Pic(dx, dy int) [][]uint8 {
resultArray := make([][]uint8, dx, dx)
for i := range resultArray {
fmt.Println(resultArray[i])
resultArray[i] = make([]uint8, dy, dy)
fmt.Println(resultArray)
for j := range resultArray[i] {
if (i+j)%30 <= 15 {
resultArray[i][j] = uint8(255)
}
}
}
return resultArray
}
However, this code which uses for i, v := range x
does not work:
func Pic(dx, dy int) [][]uint8 {
resultArray := make([][]uint8, dx, dx)
for i, ithRow := range resultArray {
ithRow = make([]uint8, dy, dy)
for j := range ithRow {
if (i+j)%30 <= 15 {
ithRow[j] = uint8(255)
}
}
}
return resultArray
}
Does this not work because ithRow
is a copy of resultArray[i]
, but not reference of it? If so, why is it not reference of it(like, what is the benefit or use case of making it copied)?