3 ms·
Okay, I've accidentally put a pointer type into an interface, now what? How do I check that the inner value is nil/not nil? Mmmmm? It's a defect in the languag
by Joker_vD 5y ago
Okay, I've accidentally put a pointer type into an interface, now what? How do I check that the inner value is nil/not nil? Mmmmm?
It's a defect in the language, plain and simple: if a pointer-to-type implements interface, then converting a nil pointer to type to the interface should result in a nil interface value (that would compare equal to nil) instead of a non-nil interface value that has nil value pointer inside it — which is a second kind of nil in anything but name. You compare it to nil, it says "not nil", then you try to use it and it blows up with panic "I am actually a nil, gotcha sucker".
- throwaway894345 5y ago> Okay, I've accidentally put a pointer type into an interface, now what? How do I check that the inner value is nil/not nil? Mmmmm? What does this even mean? If you did it by accident it sounds like a bug in your program, so fix the bug so a nil can’t be passed into the interface. If it’s not a bug but nil is a valid value, then type-assert the interface back to the concrete pointer type and check it against nil. > It's a defect in the language, plain and simple: if a pointer-to-type implements interface, then converting a nil pointer to type to the interface should result in a nil interface value (that would compare equal to nil) instead of a non-nil interface value that has nil value pointer inside it — which is a second kind of nil in anything but name. No, this would be a bug because a nil pointer and a nil interface mean different things. > You compare it to nil, it says "not nil", then you try to use it and it blows up with panic "I am actually a nil, gotcha sucker". You have the same behavior in any language with nullable references including Java, Python, C, etc. You’re complaining ultimately because you don’t understand references. In this case you have a reference type (the interface) whose value is itself a reference type and you’re upset because checking the outer reference for nil doesn’t also evaluate the inner reference; however, no mainstream language works this way and this would be very surprising behavior to people who actually understand references.
- anonymoushn 5y agoGP may have in mind that most other languages would let you write *ptr == NULL if someone handed you a pointer to a null pointer to a specific implementation of an interface even if you didn't know which specific implementation.