【发布时间】:2022-01-01 10:18:47
【问题描述】:
我是一名前 Python 开发人员,有时会为 Go 的显式性质而苦苦挣扎。 我在这里尝试重构一些代码,以便能够将方法从一个结构移动到接口的一部分。 但是这个过程对我来说似乎很奇怪,我想确认我没有做错什么。
我有以下接口、结构和方法:
type Executing interface {
Execute()
}
type MyExecuter struct {
attribut1 string
}
//The function I wish to move
func (exe1 *MyExecuter) format() string {
return fmt.sprintf ("formated : %s", exe1.attribut1)
}
func (exe1 *MyExecuter) Execute() {
//Executing
fmt.Println(exe.format())
}
func GetExecuter () Executer{
return MyExecuter{attribut1: "test"}
}
所以这里我有一个通用接口Execute,这个接口会被GetExecuter方法返回的对象访问。
现在,作为我的 Executer 实现的一部分,我想将 Format 方法作为接口的一部分移动。
所以我正在做以下事情:
type Formatting interface {
format() string
}
type Formatter struct {}
func (formatter *Formatter) format(exe1 *MyExecuter) (string) {
return fmt.sprintf ("formated : %s", exe1.attribut1)
}
所以我创建了一个新接口,一个新的空结构,并更新了我的函数以将我以前的结构作为属性。
虽然这似乎可行,但在我看来这有点令人费解。特别是我需要添加对初始对象的引用作为方法属性的部分。我在这里做错了什么,还是这是正确的方法?
【问题讨论】: