After renaming a type, I cannot access some of its methods

╄→尐↘猪︶ㄣ 提交于 2019-12-07 16:25:12

问题


In order to prevent having multiple dependencies along different files of my project and since I might change how data will be presented, I decided to make an "interface" (not in the golang sense but in an architectural way) to the draw2d package

As I didn't need anything else, I just renamed one of the types:

type CanvasContext draw2dimg.GraphicContext

In one of my modules I had the following code (path is a CanvasContext variable):

// initialization and some code omitted for clarity
path.SetFillColor(color.RGBA{0x44, 0xff, 0x44, 0xff})
path.SetStrokeColor(color.RGBA{0x44, 0x44, 0x44, 0xff})
path.SetLineWidth(5)
// some more code here
path.Close()
path.FillStroke()

Among all those method calls on path, only the FillStroke failed with the compile error:

path.FillStroke undefined (type *drawing.CanvasContext has no field or method FillStroke)

In order to prevent it I have to redefine the FillStroke, but not any other method, with:

func (cc *CanvasContext) FillStroke() {
    gc := draw2dimg.GraphicContext(*cc)
    gc.FillStroke()
}

Why do I have to redefine only that one and not any of the other calls?


回答1:


you should use struct embedding rather than type define. check the struct 'embedding' document:

but then to promote the methods of the fields and to satisfy the io interfaces, we would also need to provide forwarding methods, like this:

func (rw *ReadWriter) Read(p []byte) (n int, err error) { return rw.reader.Read(p) }

By embedding the structs directly, we avoid this bookkeeping.



来源:https://stackoverflow.com/questions/32125832/after-renaming-a-type-i-cannot-access-some-of-its-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!