Pointer and value type in golang

with the following code:

type Checkable interface {
      check() bool
  }

var _ Checkable = (*A)(nil)

type A struct {
}

func (a A) check() bool {
   return true
}

I would expect var _ Checkable = (*A)(nil) to fail because it’s A implementing the check method not *A but it compiles alright. https://play.golang.org/p/s3nYALUyY7D

https://play.golang.org/p/y5ETER4E5Uj fails to build.

Though in the inline code you do not have a space between underscore and type, which changes semantics drastically and leads to a build https://play.golang.org/p/-OSVVEylIMT

Thanks for catching the space! I just updated the question.

func (a A) check() bool {
   return true
}

and

func (a *A) check() bool {
   return true
}

are the same thing with respect to satisfying the Checkable interface.

The difference is the type of receiver the functions get. You wanna choose the second when check requires you to modify A.

are the same thing with respect to satisfying the Checkable interface.

Hmm, I am not sure they are the same. if I use

func (a A) check() bool {
   return true
}

var _ Checkable = &A{} would fail with A does not implement Checkable (check method has pointer receiver)

Yep, you’re right. I only answered your question from the the interface satisfiability angle as in https://play.golang.org/p/cuc13WHoI9S but I realize now there’s a 2x2 matrix of cases.

But going back to your original example: my best guess is that it works because you can always get the value receiver from the pointer (even if it will panic at runtime). Getting a pointer receiver from a value struct doesn’t make sense when values are copied (and thus get different pointers) as they are passed through function calls in the stack.

I’m curious to hear what other folks say though. Good question!

1 Like

Thanks a lot for sharing your thought about this! I think I get what you are saying. I think a similar comparison would be: golang can implicitly dereference pointer type but don’t automatically “reference” a value type.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.