Skip to content

Returning pointer to struct is allowed while its the struct that implements the given interface. Why? How does this work? #26901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
navgupta14 opened this issue Aug 9, 2018 · 2 comments

Comments

@navgupta14
Copy link

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

1.10.3

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

darwin/amd64

What did you do?

  1. https://play.golang.org/p/VJsb5wBoo-h - struct implementing interface
  2. https://play.golang.org/p/qpaScpD1jHd - pointer to struct implementing interface

What did you expect to see?

In 1.. when f := &Foo{}, return f should cause an error. My reason is that the struct implemented the interface not the pointer to the struct. Also, in 2., when f := Foo{}, return f causes an error. Why is there a discrepancy in behavior in the two cases. Does this have to do with the memory layout of interfaces, structs and pointers to them or some golang magic behind the scenes.

What did you see instead?

Returning struct and pointer to it both works.

@as
Copy link
Contributor

as commented Aug 9, 2018

Pointer receivers imply that an object's state is mutable. An interface that stores a non-pointer type can not modify any fields in the original value, because each method call creates a copy of the value stored in the interface and operates on that. Allowing that to work would likely be very misleading.

@ianlancetaylor
Copy link
Member

We don't use the issue trackers. Please see https://golang.org/wiki/Questions . Thanks.

I don't actually understand what you are asking. The code does not match the comments.

@golang golang locked and limited conversation to collaborators Aug 9, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants