重命名类型后,我无法访问其中的一些方法。

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

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

问题

为了避免在项目的不同文件中出现多个依赖项,并且由于我可能会更改数据的呈现方式,我决定为draw2d包创建一个“接口”(不是指golang中的接口,而是指架构上的接口)。

由于我不需要其他内容,我只是重命名了其中一个类型:

type CanvasContext draw2dimg.GraphicContext

在我的一个模块中,我有以下代码(path是一个CanvasContext变量):

// 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()

在所有对path的方法调用中,只有FillStroke方法出现了编译错误:

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

为了避免这种情况,我必须重新定义FillStroke方法,但不需要重新定义其他任何方法:

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

为什么我只需要重新定义FillStroke方法,而不是其他任何方法呢?

英文:

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

得分: 3

你应该使用结构体嵌入(struct embedding)而不是类型定义(type define)。请查看结构体“embedding”文档:

但是为了提升字段的方法并满足io接口的要求,我们还需要提供转发方法,例如:

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

通过直接嵌入结构体,我们可以避免这种繁琐的操作。

英文:

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.

huangapple
  • 本文由 发表于 2015年8月21日 02:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/32125832.html
匿名

发表评论

匿名网友

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

确定