All:
When I try to follow golang's Tour of Go:
My code is like this:
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
const x = dx
const y = dy
pic := [y][x]uint8{};
for r:=range pic {
row := pic[r]
for c := range row {
row[c] = uint8(c*r)
}
}
return pic[:]
}
func main() {
pic.Show(Pic)
}
And I got error like:
prog.go:6:8: const initializer dx is not a constant
prog.go:7:8: const initializer dy is not a constant
I am pretty new to Go, I wonder what this error means, and if I want to build an array first(other than using make() to build slice), how can I pass the length of array?
The Error
The error comes from trying to define a constant from a variable. In Go, constants must be defined as literals or expressions built from other constants. Your x
and y
are defined differently depending on the input of the Pic
function. In general, constants are defined at compile time.
For example the following are fine in Go:
const w = 100
const x = 200
const y = w + x
const z = x + y + 300
But the following is not:
var x = 100
const y = x + 10
and this second example is essentially what is happening in your code since dx
and dy
vary depending on the input to the Pic
function.
If you're coming from JavaScript, which also has the const
keyword, this might seem like strange behavior. In JavaScript a constant is basically just a variable that can't be changed after it is declared. In Go, a constant is more constant than in JS.
Check out this post for more on constants in Go: https://blog.golang.org/constants
Creating the Array
Array sizes have similar constraints to constant values in Go. In this example, if you try to set the Array's size equal to dx
or dy
, you will get the error:
non-constant array bound dx
Thus you will have to use a Slice in this example. The simplest way would be to define your Slice with length dy
like:
pic := make([][]uint8, dy)
There are no constant values. For example,
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
p := make([][]uint8, dy)
for x := range p {
p[x] = make([]uint8, dx)
for y := range p[x] {
p[x][y] = uint8(x * y)
}
}
return p
}
func main() {
pic.Show(Pic)
}
Playground: https://play.golang.org/p/JQwGhfBth0o