Why not add a keyword to facilitate the implementation of the interface mechanism | 为什么不增加一个关键字用于方便的实现接口机制


(Wangfuyao) #1

在 go 中实现一个接口,需要自己找到并实现 interface 下面所有的函数,在代码量非常多的项目中,这么做非常不方便,为什么不像其他语言那样,用一个 impl 关键字将实现一个接口的所有函数聚合到一处 。就像下面的例子:

To implement an interface in go, you need to find and implement all the functions of the interface. In a project with a lot of code, this is very inconvenient. Why not use an impl keyword to generate all the functions of an interface together.Like the example below:

type (  
        Interface interface {
	     Len() int
	     Less(i, j int) bool
	     Swap(i, j int)
        }
	CountDownAction struct {
		Action  int    `json:"action"`
	}
)
var CountDownList []CountDownAction

CountDownList impl  Interface{
    func (receiver CountDownList) Len() int {
	    return len(receiver)
    }
    func (receiver CountDownList) Less(i, j int) bool {
	    return receiver[i].Action <= receiver[j].Action
    }

    func (receiver CountDownList) Swap(i, j int) {
	    receiver[i], receiver[j] = receiver[j], receiver[i]
    }

}


这样,IDE 就可以为我们省下不少的工作

In this way, the IDE can save a lot of work for us.


(Jakob Borg) #2

The IDE can do this anyway, though. Goland does.


(Wangfuyao) #3

How does goland do it, can you guide it? thanks :grinning:


(Jakob Borg) #4

I don’t use Goland, it was just the first result from the obvious web search. Look at “code generation” here: https://www.jetbrains.com/go/features/


(Wangfuyao) #5

thanks.i get it :grinning: