4 ms·
It's not clear which kind of nil interface you mean. :) In Go, interface variables are a pair of values: a pointer to the concrete value stored in the variable
by parenthephobia 10y ago
It's not clear which kind of nil interface you mean. :)
In Go, interface variables are a pair of values: a pointer to the concrete value stored in the variable, and a pointer to the type of that concrete value (i.e. the actual struct).
So there are essentially three kinds of nil in Go: a raw nil pointer, an interface variable with both nil value and type pointers, and an interface variable with a nil value pointer, but a non-nil type pointer.
One way that the two "interface nils" differ is that, to follow the article's example, if you have a Cat variable containing a nil *Tabby, you can invoke Meow on it, and it'll print meow. This works because Tabby's Meow doesn't try to dereference its pointer-to-Tabby. However, if you have a Cat variable that's completely empty, invoking Meow on it will fail.
- bluejekyll 10y agoThanks. This is a great succinct example.
- thaumasiotes 10y agoWhat is the conceptual difference between a raw nil pointer, e.g. var t *Tabby = nil, and an interface with nil value and non-nil type? The raw pointer also has nil value and non-nil type.
- Matthias247 10y agoThe difference is that on a nil-interface you can't call a method, it will panic. On a non-nil interface it will always call the method, wether a nil-pointer is stored as the receiver or not. It a nil pointer is stored it will call the method will it, and the method may still do something useful. It can be theoretically be used to implement some interfaces without any backing object at all (singletons, pure functions, ...), which is a difference to most other programming languages.
- thaumasiotes 10y agoYou're explaining the difference between two things, but not the two things I asked about.
- Matthias247 10y agoSorry - the question is not immediatly understandable. If you mean how 'var t *Tabby = nil' is different from the interface representation: For this one no type information is stored at runtime. It's only a single pointer. Whereas an interface at runtime is always represented by 2 fields, a pointer and a type field.
- thaumasiotes 10y agoThanks. It didn't occur to me that non-interface types might not actually carry type information.