go - Pointer receiver and value receiver in Exercise:Image -


i quite new go, , quite confused receiver idea in go. exercise tour of go.

question body:

remember picture generator wrote earlier? let's write one, time return implementation of image.image instead of slice of data.

define own image type, implement necessary methods, , call pic.showimage.

bounds should return image.rectangle, image.rect(0, 0, w, h).

colormodel should return color.rgbamodel.

at should return color; value v in last picture generator corresponds color.rgba{v, v, 255, 255} in one.

here code:

package main  import "golang.org/x/tour/pic" import "image" import "image/color"   type image struct{}  func (img *image) bounds() image.rectangle{     w := 100     h := 100     return image.rect(0,0,w,h) }  func (img *image) colormodel() color.model{     return color.rgbamodel }  func (img *image) at(x int, y int) color.color{     return color.rgba{uint8(x^y), uint8(y/2), 255,255} }  func main() {     m := image{}     pic.showimage(m) } 

and report compile error:

command-line-arguments ./compile110.go:26: cannot use m (type image) type image.image in argument pic.showimage: image not implement image.image (at method has pointer receiver)


my understanding receivers of methods, alright set them either pointers or values. however, when set "*image" "image", errors go away.

can me this?


the answers provided below sufficient question raised. however, seems pointer , value receivers thingy can bit more complicated.

from effective go:

the rule pointers vs. values receivers value methods can invoked on pointers , values, pointer methods can invoked on pointers. rule arises because pointer methods can modify receiver; invoking them on value cause method receive copy of value, modifications discarded. language therefore disallows mistake. there handy exception, though. when value addressable, language takes care of common case of invoking pointer method on value inserting address operator automatically.

hope of well.

when use interfaces in go need make sure instance using implements interface. in go-tour example problem, image not satisfy image.image interface, &image does.

as such need either change method signatures take value receivers make image work, or pass &image pic.showimage function since pointer image implement interface.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -