I am just learning Go and wrote the following struct (Image
) to implement the image.Image
interface.
package main
import (
"image"
"image/color"
"code.google.com/p/go-tour/pic"
)
type Image struct{}
func (img Image) ColorModel() color.Model {
return color.RGBAModel
}
func (img Image) Bounds() image.Rectangle {
return image.Rect(0, 0, 100, 100)
}
func (img Image) At(x, y int) color.Color {
return color.RGBA{100, 100, 255, 255}
}
func main() {
m := Image{}
pic.ShowImage(m)
}
If I just import image/color
and not import image
, image.Rect
is undefined. Why? Shouldn't image/color
already cover the methods and properties of image
?
Also, if I change the function receivers from (img Image)
to (img *Image)
, an error arises:
Image does not implement image.Image (At method requires pointer receiver)
Why is that? Doesn't (img *Image)
indicate a pointer receiver?
If you check out the source for the image
package and its sub-packages, you will see that image/color
does not depend on image
at all, so it never imports it.
image
does however import image/color
For the second part of your question, where you change all of the receivers to pointers, that means you should also be passing an Image pointer to ShowImage
:
func main() {
m := Image{}
pic.ShowImage(&m)
}
Methods defined on a pointer receiver must be accessed on a pointer. But methods defined on just the struct can be accessed from a pointer or the value.
Here is some documentation explaining the difference between a pointer or a value receiver of a method: