登录
首页 >  Golang >  Go问答

Golang:如何对多种结构使用共享方法

来源:stackoverflow

时间:2024-02-08 18:54:24 353浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《Golang:如何对多种结构使用共享方法》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

如何将相同的逻辑应用于不同的结构?

例如,更新结构体的字段。 我想为结构 a 和 b 共享相同的 updatename 逻辑

a 和 b 来自不同的包。

// model/a.go
type a struct {
   name  string
   total int64
   date  time.time
}
// model/b.go
type b struct {
   name  string
   price float64
   total int64
   date  time.time
}

希望将重复的逻辑合并为一个。

// service/a.go
func updatename(data *a) {
   data.name = "new"
}

// service/b.go
func updatename(data *b) {
   data.name = "new"
}

我想使用一个接口来解耦。

此外,如何将接口解析为参数。

type DataSetter() interface {
    SetName(name string)
    SetTotal(total int64)
}

感谢您帮助我解决这个基本问题。


正确答案


对于像您所示的简单值分配,通常最好简单地公开该字段:

type a struct {
   name string
   ...
}

...
func f(a *a) {
   a.name="x"
}

您可能会考虑嵌入一个通用结构:

type common struct {
   name string
}

func (c *common) setname(s string) {
   c.name=s
}


type a struct {
   common
   ...
}

type b struct {
   common
   ...
}

func f(a *a) {
   a.setname("x")
}

您可以使用代表通用类型功能的接口:

type WithName interface {
   SetName(string)
}


func f(x WithName) {
   x.SetName("x")
}


func g(a *A) {
   f(a)
}

func h(b *B) {
   f(b)
}

但是您不会只想对 setname 执行此操作。

今天关于《Golang:如何对多种结构使用共享方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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