Tour Exercise Question

I’m struggling to make my code run in this exercise of the Tour of Golang:

https://tour.golang.org/moretypes/18

The main function call just runs: pic.Show(Pic). Is that part of the problem? Presumably it should run pic.Show(Pic(3,3)) or something similar, since Pic takes two arguments?

I have tried to run this, of course, and it fails, so my code is also wrong. But my code is so simple that I don’t understand how it can be wrong, and the error message doesn’t help:

    package main
    import "golang.org/x/tour/pic"

    func Pic(dx, dy int) [][]uint8 {

    	output := [][]uint8{
    		[]uint8{0, 0, 0},
    		[]uint8{0, 255, 0},
    		[]uint8{0, 0, 0},
    	}

    	return output
    }

    func main() {
    	pic.Show(Pic)
    }

panic: runtime error: index out of range [3] with length 3

goroutine 1 [running]:
golang.org/x/tour/pic.Show(0x4eea60)

  • /tmp/gopath773663214/pkg/mod/golang.org/x/tour@v0.0.0-20210305160921-b3263fcf7749/pic/pic.go:36 +0x1a6*
    main.main()
  • /tmp/sandbox350473227/prog.go:27 +0x2d*

I think I’ve answered my own question. pic.Show requires a function which returns [][]uint8, not [][]uint8. With that in mind, I think that I was either returning a function which returns [3][3]uint8, or just [3][3]uint8, neither of which was right (I think that is what " index out of range [3] with length 3" was trying to tell me).

That said, it is a little confusing, because I’ve still written a function which returns a bounded array, but it is bounded by arguments passed to the function. I would still appreciate some insight into why my first attempt didn’t just plot a 3x3 pixel square.

My final solution is:

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {

	var output [][]uint8

	for len(output) < dy {
		output = append(output, make([]uint8, dx))
	}

	for y:=0 ; y<dy; y++ {
		for x:=0 ; x<dx; x++ {
			output[y][x] = uint8((x+y))
		}
	}

	return output
}

func main() {
	pic.Show(Pic)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.