-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: Go 2: non-copyable structs by default #30450
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
Comments
This would make it impossible to use structs as map keys. |
Good point. Most structs shouldn't be used as map keys, but we want that to work. What about having a way to mark structs as copyable then? Some small keyword, perhaps? Obviously copyable structs can't contain non-copyable structs. |
(I'm assuming we don't want to open the box of comparable but non-copyable types.) |
Many structs are safe to copy, though. The sort of thing you're asking for is a property of languages with a different philosophy from Go and doesn't fit well in Go's model. |
Would it work if it used package boundaries? Structs with inaccessible fields are non-copyable? |
Thanks, that's useful background. Should I write up the accessibility-based proposal in more detail? |
A current way to declare that a struct is not copyable is to add both a We are not going to change the default for how structs work in Go, so closing this specific issue. |
It looks embedding a non-exported struct doesn't prevent the methods being exposed: https://play.golang.org/p/oahXcIL11j3 |
It looks std packages use non-embedding general
|
Most structs are actually not safe to copy. Most code handles structs by pointer because it is the best way to avoid accidentally copying it. (And there's hard-coding to prevent sync.Mutex being copied because of how often that mistake got made!)
Go 2 should accept this reality and make structs non-copyable by default. The copy() method could be extended to allow struct copying, and people who really want copyable structs can provide a method to call copy() for you.
Note that this doesn't stop moves of structs, e.g. returning them. Accepting them by value is a more complex question, since it introduces the possibility of an "empty" variable in many cases.
The text was updated successfully, but these errors were encountered: