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?

kovac
  • 4,945
  • 9
  • 47
  • 90
  • 2
    See [Pass Values](https://github.com/golang/go/wiki/CodeReviewComments#pass-values) and [Receiver Types](https://github.com/golang/go/wiki/CodeReviewComments#receiver-type) for recommendations. – Charlie Tumahai Feb 24 '19 at 04:32

1 Answers1

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.

Adrian
  • 1,973
  • 1
  • 15
  • 28
  • 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? – kovac Feb 24 '19 at 04:56
  • 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 – Adrian Feb 24 '19 at 05:02