A Tour of Go の Exercise を実施したときのメモ。
- 「自分の Image 型を定義し、 インタフェースを満たすのに必要なメソッド を実装し、〜」のインターフェイス
type Image interface {
// ColorModel returns the Image's color model.
ColorModel() color.Model
// Bounds returns the domain for which At can return non-zero color.
// The bounds do not necessarily contain the point (0, 0).
Bounds() Rectangle
// At returns the color of the pixel at (x, y).
// At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
// At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
At(x, y int) color.Color
}
- 問題に記載してあるとおりに実装する(以下、問題から引用)
- Bounds は、
image.Rect(0, 0, w, h)
のようにしてimage.Rectangle
を返すようにします。- →ここの
w
とh
はImage{}
で指定した値になるので、type Image
にw, h int
を追加
- →ここの
-
ColorModel
は、color.RGBAModel
を返すようにします。- →これは、ほんとにそのまま。
-
At
は、ひとつの色を返します。 生成する画像の色の値 v をcolor.RGBA{v, v, 255, 255}
を利用して返すようにします。- →これもほぼそのままだが、
v
の定義(uint8(x * y)
)が必要。
- →これもほぼそのままだが、
- Bounds は、
exercise-images.go
package main
import "golang.org/x/tour/pic"
import (
"image"
"image/color"
)
type Image struct{
w, h int
}
func (img Image) ColorModel() color.Model {
return color.RGBAModel
}
func (img Image) Bounds() image.Rectangle {
return image.Rect(0,0,img.w,img.h)
}
func (img Image) At(x, y int) color.Color {
v := uint8(x * y)
return color.RGBA{v, v, 255, 255}
}
func main() {
m := Image{100, 100}
pic.ShowImage(m)
}