Home > Net >  Interface implementation enforcement in Go
Interface implementation enforcement in Go

Time:10-29

I have simple Go code:

type MyInterface interface {
    Do()
}

type Doer struct{}

func (d *Doer) Do() {}

// Option 1
var _ MyInterface = (*Doer)(nil)

// Option 2
var _ MyInterface = &Doer{}

What is the downside of enforcing the interface with option 1 (which is widely used and advised everywhere) as opposed to option 2?

If we are discarding the result, what's the harm of instantiating a real object instead of pointer?

I understand that Option 2 is probably one millisecond slower as it does allocation of memory for the struct and also there is another millisecond for GC to clean it up probably, but all of it is happening only at startup and does not affect the runtime.

Are those my correct or do I miss anything?

CodePudding user response:

The analysis in the question is good. Here are two additional points:

Option 1 works with any type. Option 2 only works for types with composite literal syntax.

Here's an example:

type IntDoer int

func (d *IntDoer) Do() {}

// Option 1
var _ MyInterface = (*IntDoer)(nil)

// Option 2 DOES NOT COMPILE
var _ MyInterface = &IntDoer{} 

Option 2 may not have any runtime penalty. It's possible that the compiler optimizes out the allocation.

  • Related