登录
首页 >  Golang >  Go问答

将方法转化为接口的成员

来源:stackoverflow

时间:2024-02-21 08:48:26 286浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《将方法转化为接口的成员》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我是一名前 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方法返回的对象访问。

现在,作为我的一个执行器实现的一部分,我想将 format 方法移动为接口的一部分。

所以我正在做以下事情:

type Formatting interface {
    format() string
}

type Formatter struct {}

func (formatter *Formatter) format(exe1 *MyExecuter) (string) {
    return fmt.sprintf ("formated : %s", exe1.attribut1)
}

因此,我创建了一个新的界面、一个新的空结构,并更新了我的函数以将我以前的结构作为属性。

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


正确答案


您的 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 定义方法。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将方法转化为接口的成员》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>