Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go — how to handle common fields between struct types

Tags:

types

struct

go

If I have two types:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}

Is there any way to achieve the following without needing two methods, given that both access identically-named fields and return the sum of them?

func (a *A) Sum() int {
     return a.X + a.Y
}

func (b *B) Sum() int {
     return b.X + b.Y
}

Of course, were X and Y methods, I could define an interface containing these two methods. Is there an analogue for fields?

like image 705
Matthew H Avatar asked Mar 04 '13 01:03

Matthew H


People also ask

What are nested structures in Golang?

In Go, A structure which is a field of another structure is known as the Nested Structure.

Can Golang structs have methods?

You can also add methods to struct types using a method receiver. A method EmpInfo is added to the Employee struct.

Why can't we create an object within structure in the same structure?

you can not put a whole struct inside of itself because it would be infinitely recursive.

Can a struct have an interface Golang?

Like a struct an interface is created using the type keyword, followed by a name and the keyword interface . But instead of defining fields, we define a “method set”. A method set is a list of methods that a type must have in order to “implement” the interface.


1 Answers

Embed A in B.

type A struct {
      X int
      Y int
}

func (a *A) Sum() int {
     return a.X + a.Y
}

type B struct {
      *A
      Z int 
}

a := &A{1,2}
b := &B{&A{3,4},5}

fmt.Println(a.Sum(), b.Sum()) // 3 7

http://play.golang.org/p/fjT9c-m_Lj

But no, there's no interface for fields. Only methods.

like image 151
the system Avatar answered Oct 20 '22 20:10

the system