News for hackers. Stuff that matters.
Re:Understand Go pointers by brandonbloom on Wednesday April 26, 2017 @02:03PM (#14205411)
I think others answered the question of pointers vs not-pointers reasonably well, but your question implies you already understood that. The interesting thing to me is that they _did_ make some pointer types implicit: maps, chans, etc. Moreover, you can easily hide a pointer in a struct, such that the use site gives no hint as to whether or not you're going to have "spooky action at a distance" for mutations.

Given this, a more interesting question is "Why can't I define types that are implicitly always pointers?" I don't know the answer to that. My guess would be path-dependent design. As I understand it, even maps and chans were explicitly pointers for a long while in the early history of Go.

I've found that I can classify all structs in to two groups:

1) simple record values with all public fields; rare methods for convenience or specific polymorphism. 2) encapsulated machines with all private fields; only accessed through rich method interface.

Any blending of public and private fields has turned out to be a mistake in my experience. For record types, the implicit copying is valuable for passing data around. With encapsulated machines, I almost always want all usages to be a pointer. I wish I could define types like this:

    type MyMachine *struct {
        ...private fields...
    }
Which would basically compile like this:

    type machineState struct {
        ...public fields...
    }

    type MyMachine struct {
        *machineState
    }
One problem with this approximate macro-expansion is that you can't use "nil" for MyMachine, instead you need to use (MyMachine{}) as a zero value. I'd change that across the language too and just make nil a proper polymorphic literal zero value for any type.

There are no comments on this comment yet.