# Golang. Two-dimensional slices (2D)

From chapter 18 of Go tour.. In general, the tasks in this ‘tour’ are quite itchy B) So… Implement the `Pic` function. It should return a fragment of length `dy`, each element of which is a fragment of `dx` 8-bit unsigned integers. When you run the program, it will display your picture by interpreting the integers as grayscale (or blue) values. It will draw something like the picture on the left..

The choice of image is up to you. Interesting functions include (x+y)/2, x*y or x^y.

(You must use a loop to select each `[]uint8` within `[][]uint8`.)

(Use `uint8(intValue)` to convert between types).

Comment:

The main problem for beginners is figuring out why the hell nothing gets passed to Pic(). The secret is to look under the hood of pic.Show.

The next problem is figuring out two-dimensional slises. This example will help you with that:

```package main

import (
"fmt"
)

func main() {
slice := make([][]uint8, 5)
fmt.Printf("make([][]uint8, 5) = %v\n", slice)

for y := range slice {
slice[y] = make([]uint8, 3)
}

fmt.Printf("+ make([]uint8, 3) = %v\n", slice)
}
```

In general, the assignment is rather harsh for teaching newcomers 🙂 It’s too complicated… Good for nerds, bad for casuals. But that’s about it. Chew on the granite, it will come in handy!

Solution:

```package main

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

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

// dx and dy is equal to 256 in pic.Show()

// allocate slice ([[] [] ... []])
slice := make([][]uint8, 256)
//fmt.Printf("%v\n", slice)

// add 2nd dimension of slice [[0 0 ..] ... [.. 0 0]]
for y := range slice {
slice[y] = make([]uint8, 256)

// put data to each element
for x := range slice[y] {
slice[y][x] = uint8(x * y)
}
}

return slice
}

func main() {

pic.Show(Pic)
}
```

p.s.
I purposely put 256, not dy/dx, to make the mechanism of graphing clearer 🙂

This entry was posted in Go (en). Bookmark the permalink.