Home > OS >  Golang: How to use same the method for different structures
Golang: How to use same the method for different structures

Time:01-11

How can I apply the same logic to different structures?

For example, update a struct's field. I want to share the same UpdateName logic for both struct A and B

A and B are from different packages.

// 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
}

Hopefully combine duplicated logic as one.

// service/a.go
func UpdateName(data *A) {
   data.Name = "NEW"
}

// service/b.go
func UpdateName(data *B) {
   data.Name = "NEW"
}

I'd like to use an interface for decoupling.
Furthermore, How can I parse interface as a parameter.

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

Thanks for helping me with this basic question.

CodePudding user response:

For simple value assignments like you showed, it is often better to simply expose the field:

type A struct {
   Name string
   ...
}

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

You might consider embedding a common struct:

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")
}

You can use an interface that represents the functions of the common type:

type WithName interface {
   SetName(string)
}


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


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

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

But you wouldn't want to do this for just SetName.

  •  Tags:  
  • Related