4 ms·
Go's simplicity is merely syntactical. The semantics can be subtle and not entirely aligned with intuition honed after x years of working with C-like language X
by eternalban 11y ago
Go's simplicity is merely syntactical. The semantics can be subtle and not entirely aligned with intuition honed after x years of working with C-like language X.
This is an observation and not a critique.
> I learned yesterday that `x == nil` can return false even if x is nil so long as ...
In other words:
http://play.golang.org/p/YV5ylbQN4j http://play.golang.org/p/YV5ylbQN4j
Thanks for the heads-up! That was news to me.
- tptacek 11y agoWhen does it make sense to compare a string with nil?
- eternalban 11y agoIt doesn't but the function admits a T. It actually makes perfect sense, it is just a bit subtle.
- oconnor663 11y agoIn the playground you have there, the string `v` is implicitly initialized to the empty string, which is not equal to nil. I'm referring to a different condition, where two different values are explicitly set to nil. Check this out: https://play.golang.org/p/qMmg7yOAKO https://play.golang.org/p/qMmg7yOAKO
- infogulch 11y agoYes this is what trips many people up. One reason `(* T)(nil) != nil` is because a `(* T)(nil)` can still have pointer methods called on it, and it can still work fine (as long as the receiver is never dereferenced, of course): https://play.golang.org/p/rup5cqapEU https://play.golang.org/p/rup5cqapEU
- falcolas 11y agoActually, the issue mentioned by the OP is covered here: http://golang.org/doc/faq#nil_error http://golang.org/doc/faq#nil_error Basically, if you pass 'nil' of one type into an argument which accepts an interface of another type, the nil is no longer nil, but an interface wrapper around a nil (which is not nil). So: var buf *bufio.Reader // a nil value if this is passed into a function with a signature of func foo(buf io.Reader) then when in function foo: foo(buf) // valid, and buf is nil here //inside foo: if buf != nil { // but buf is not nil here, so this is true buf.Read() // Panics because nil has no function Read.
- pcwalton 11y agoThe post you were replying to was talking about whether the behavior is intuitive, not whether it is documented.
- Redoubts 11y agoI'm confused, how is that different from https://play.golang.org/p/rup5cqapEU https://play.golang.org/p/rup5cqapEU where calling on the nil value of T seems to work.