2

Let's say I have a struct implementing an interface like below:

type IFace interface {
   Method1()
   Method2()
   Method3()
} 


type Face struct {
  Prop1 string
  Prop2 int
}


// IFace implementation here...

Now if I have method that accepts IFace is it better to design it to accept a pointer to that interface of value?

  1. Accept pointer:
func DummyMethod(f *IFace) {
   (*f).Method1()
}
  1. By value:
    func DummyMethod(f IFace){
      f.Method1()
    }

My first guess is since these are structs, probably it's better to pass by value? Or is there a rule of thumb considering the size and nature of the struct when to start passing a pointer?

Also, when we are adding methods to a struct is it better to pass a pointer to the struct or it's value?

1
  • 2
    See Pass Values and Receiver Types for recommendations. Commented Feb 24, 2019 at 4:32

1 Answer 1

1

When passing interface type as a parameter, pass it by value, note that interface type itself would be a pointer to concrete type.

When it comes to the performance side, using interface comes with the price too, it simply cannot be inlined.

I guess it is fine to use interface with dozen calls per request/entry point, but if an app has to make thousands+ invocations, benchmark your code first before making a call.

Sign up to request clarification or add additional context in comments.

2 Comments

So even in the 2 case, what is actually passed is the value of the pointer to the concreate type and no copying of the concrete type happens?
when passing a value there is always a copy involved, either copying a pointer or concrete value. Since the interface is already a pointer to a concrete type, no concrete type copying happens

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.