←back to thread

Go subtleties

(harrisoncramer.me)
235 points darccio | 1 comments | | HN request time: 0s | source
Show context
rowanseymour ◴[] No.45666258[source]
Ah the old nil values boxed into non-nil interfaces. Even after 8 years writing go code almost every day this still bites me occasionally. I've never seen code that actually uses this. I understand why it is the way it is but I hate it.
replies(4): >>45666614 #>>45666792 #>>45666859 #>>45669163 #
aatd86 ◴[] No.45666792[source]
Yes, that'a bit too late after ten+ years perhaps but I wished we had a nil type and checking whether the interface is empty was a type assertion. In all other cases, like any(2) == 2, we compare the values.

Then again that would mean that the nil identifier would be coerced into a typed nil and we would check for the nilness of what is inside an interface in any(somepointer) == nil.

wrt the current behavior, it also makes sense to have a nil value that remains untyped. But in many other cases we do have that automatic inference/coercion, for instance when we set a pointer to nil.(p = nil)

That's quite subtle and that ship has sailed though.

replies(2): >>45666878 #>>45668625 #
rowanseymour ◴[] No.45666878[source]
Agree the ship has likely sailed, but if it could be addressed wouldn't it be nice to remove nil value interfaces altogether? Maybe start by letting new interface types declare/annotate that they don't box nil values? Then one day that becomes the default. Oh well.
replies(2): >>45667583 #>>45670974 #
aatd86 ◴[] No.45667583[source]
Oh that's probably doable. Introducing something like this is a bit orthogonal to the point above, but yes.

It's not straightforward but probably something that will be considered at some point I reckon when thinking about making union interfaces first class. That will require to track a not nil typestate/predicate in the backend, something like that I guess.

replies(1): >>45667667 #
rowanseymour ◴[] No.45667667[source]
Having pondered on a bit more.. I think it's the struct that would declare that it's not usable as nil, and that in turn would tell the runtime not to box it if it's nil. That would also help the compiler (and copilot etc) spot calls on nil pointers which will panic.
replies(1): >>45668969 #
1. aatd86 ◴[] No.45668969{3}[source]
But that information disappears when you assign to an interface variable/container that is nillable. It requires an assertion to recover the info about the value inside the interface being not nil.

basically `if v.(nil){...}

creates two branches. In one we know v is not nil (outside the if block) and it can therefore be assigned to non nillable variables so to speak...