0

I’ve a method which should get the different types , how it’s suggested to solve this instead duplicate functions that doing basically the same… (I want to avoid creating wrapper struct....)

type A1 struct {
    Spec              A1Spec    `json:"spec,omitempty"`
    Status            A1Status `json:"status,omitempty"`
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
}

type B1 struct {
    Spec               B1Spec   `json:"spec,omitempty"`
    Status            B1Status `json:"status,omitempty"`
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
}

func ExecuteA1(ctx context.Context, a1 A1, Client client.Client) error {

if a1.Spec.Type == "test" {….


}}


func ExecuteB1(ctx context.Context, b1 B1, Client client.Client) error {

if  b1.Spec.Type == "test" {….

}
….}

Both functions are doing the same but get different type, I want to avoid creating two functions, how its suggested to solve this?

https://play.golang.org/p/kV7s3LRd-eh

PJEM
  • 557
  • 7
  • 33

1 Answers1

2

By using interfaces. Have both A1 and B1 implement an interface which has a method to acquire (return) the type. Then you only need a single Execute() function which expects a value of this interface type, can call the method defined by the interface. And then you can pass either a value of A1 or B1, or any other type that implements the interface.

For example:

type HasType interface {
    GetType() string
}

func (a A1) GetType() string {
    return a.Spec.Type
 }

func (b B1) GetType() string {
    return b.Spec.Type
}

func Execute(ctx context.Context, foo HasType, Client client.Client) error {
    if foo.GetType() == "test" {
    }
}

You may call it like:

var a A1 = ...
var b B1 = ...

Execute(ctx, a, client)
Execute(ctx, b, client)

See Why are interfaces needed in Golang?

Also note that in this specific example you could just pass the type instead of A1 and B1, so the interface and method declarations could be left out.

E.g. you could create Execute() like this:

func Execute(ctx context.Context, typ string, Client client.Client) error {
    if typ == "test" {
    }
}

And call it like this:

var a A1 = ...
var b B1 = ...

Execute(ctx, a.Spec.Type, client)
Execute(ctx, b.Spec.Type, client)
icza
  • 389,944
  • 63
  • 907
  • 827