【问题标题】:Refactoring method to be part of an interface将方法重构为接口的一部分
【发布时间】: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)
}

所以我创建了一个新接口,一个新的空结构,并更新了我的函数以将我以前的结构作为属性。

虽然这似乎可行,但在我看来这有点令人费解。特别是我需要添加对初始对象的引用作为方法属性的部分。我在这里做错了什么,还是这是正确的方法?

【问题讨论】:

    标签: go interface


    【解决方案1】:

    您的Executer 实现已经实现了Formatting 接口:

    type Executing interface {
        Execute()
    }
    
    type Formatting interface {
        format() string
    }
    
    func (exe1 MyExecuter) format() string {
        return fmt.sprintf ("formated : %s", exe1.attribut1) 
    }
    
    
    func (exe1 MyExecuter) Execute() {
        //Executing
        fmt.Println(exe.format())
    }
    
    v:=MyExecuter{}
    // Here, v implements Executing and Formatting interfaces
    
    

    这里需要注意一点:您的代码显示了指针接收器。这意味着这些方法是为*MyExecuter 定义的,但不是为MyExecuter 定义的。因此,您必须将指针传递给结构实例才能使其工作。或者,就像我在上面所做的那样,使用值接收器,以便为 MyExecuter*MyExecuter 定义方法。

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多