英文:
Why must I import both "image/color" and "image"?
问题
我只是学习Go,并编写了以下结构体(Image
)来实现image.Image
接口。
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)
}
如果我只导入image/color
而不导入image
,image.Rect
会被定义为未定义。为什么?难道image/color
不应该已经包含image
的方法和属性吗?
另外,如果我将函数接收者从(img Image)
更改为(img *Image)
,会出现错误:
Image does not implement image.Image (At method requires pointer receiver)
为什么会这样?(img *Image)
不是表示指针接收者吗?
英文:
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?
答案1
得分: 12
如果你查看image包的源代码及其子包,你会发现image/color不依赖于image,因此它从未导入过它。
对于你问题的第二部分,当你将所有的接收者都改为指针时,这意味着你应该将一个Image指针传递给ShowImage
:
func main() {
m := Image{}
pic.ShowImage(&m)
}
在指针接收者上定义的方法必须通过指针访问。但是在结构体上定义的方法可以通过指针或值访问。
这里有一些解释方法的指针接收者和值接收者之间的区别的文档:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论