Golang练习:方法中缺少图像。

huangapple go评论81阅读模式
英文:

golang exercise:images missing at method

问题

我正在解决这个练习:https://tour.golang.org/methods/25 中的图像问题,但是遇到了一个问题。以下是我的代码:

package main

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

type Image struct{
	image *image.RGBA	
}

func main() {
	rect := image.Rect(0,0,255,255)
	myImage := image.NewRGBA(rect)
	m := Image{myImage}
	pic.ShowImage(m)
}

它给我报错了:

tmp/sandbox089594299/main.go:16: cannot use m (type Image) as type image.Image in argument to pic.ShowImage:
	Image does not implement image.Image (missing At method)

但是image.NewRGBA返回的是*NRGBA,而*NRGBA确实有一个At()方法。而且我认为,由于At()方法是image.Image接口所要求的最后一个方法,它应该能找到其他两个必需的方法...那么At()方法出了什么问题呢?

image.NRGBA:https://golang.org/pkg/image/#NRGBA

image.Image接口:https://golang.org/pkg/image/#Image

英文:

I am wokring through the exercise:images at https://tour.golang.org/methods/25 and I have run into a problem. Here is my code...

package main

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

type Image struct{
	image *image.RGBA	
}

func main() {
	rect := image.Rect(0,0,255,255)
	myImage := image.NewRGBA(rect)
	m := Image{myImage}
	pic.ShowImage(m)
}

it gives me the error...

tmp/sandbox089594299/main.go:16: cannot use m (type Image) as type image.Image in argument to pic.ShowImage:
	Image does not implement image.Image (missing At method)

But image.NewRGBA returns a *NRGBA and that does indeed have an At() method. Also I assume since the At() method is the last method required by the image.Image interface then it is finding the other two required methods...so what is up with the At()?

image.NRGBA: https://golang.org/pkg/image/#NRGBA

image.Image interface: https://golang.org/pkg/image/#Image

答案1

得分: 1

你的类型Image没有实现At方法。如果你希望你的类型继承*image.RGBA实现的方法,可以使用匿名字段:

type Image struct {
    *image.RGBA
}

参考链接:https://golang.org/doc/effective_go.html#embedding。

英文:

Your type Image does not implement the At method. If you want your type to inherit the methods implemented by *image.RGBA, use an anonymous field:

type Image struct{
     *image.RGBA   
}

See https://golang.org/doc/effective_go.html#embedding.

huangapple
  • 本文由 发表于 2016年10月11日 22:43:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/39979956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定