A Tour of Go - 解答

Golangを勉強しています。

Excercies: rot13Reader

https://go-tour-jp.appspot.com/methods/23

io.Reader を実装し、 io.Reader でROT13 換字式暗号( substitution cipher )をすべてのアルファベットの文字に適用して読み出すように >rot13Reader を実装してみてください。

package main

import (
    "io"
    "os"
    "strings"
)

type rot13Reader struct {
    r io.Reader
}

func (r13 *rot13Reader) Read(buf []byte) (int, error) {
    n, e := r13.r.Read(buf)

    for i := 0; i < n; i++ {
        if buf[i] < 'A' || buf[i] > 'z' {
            continue
        }
        if buf[i] < 'Z' && buf[i] > 'a' {
            continue
        }

        if buf[i] < 'A'+13 || buf[i] < 'a'+13 {
            buf[i] += 13
        } else if buf[i] < 'O'+13 || buf[i] < 'o'+13 {
            buf[i] -= 13
        }
    }
    return n, e
}

func main() {
    s := strings.NewReader("Lbh penpxrq gur pbqr!")
    r := rot13Reader{s}
    io.Copy(os.Stdout, &r)
}

Exercise: Images

自分の Image 型を定義し、 インタフェースを満たすのに必要なメソッド を実装し、 pic.ShowImage を呼び出してみてください。

package main

import (
    "image"
    "image/color"

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

type Image struct {
    x int
    y int
}

func (img Image) Bounds() image.Rectangle {
    return image.Rect(0, 0, img.x, img.y)
}

func (img Image) ColorModel() color.Model {
    retuarn color.RGBAModel
}

func (img Image) At(x, y int) color.Color {
    v := uint8(x ^ y)
    return color.RGBA{v, v, 255, 255}
}

func main() {
    m := Image{256, 256}
    pic.ShowImage(m)
}