On Mon, Feb 17, 2020 at 11:18 AM <kloste...@gmail.com> wrote:

> Out of curiosity: Could you please tell when calling methods on nil
> pointers is useful?
>

In general, linked datastructures - like linked lists or trees. As a
somewhat trivial example, consider this:
https://play.golang.org/p/Y-4aSVLzEFO
Interpreting a nil-pointer as "an empty tree" makes a lot of the
traversal-algorithms easier to express.
I also have an internal package that wraps the openat/mkdirat/linkat/…
class of syscalls, to make it possible to still read/write a directory that
has been bind-mounted over. It uses a struct to encapsulate the
file-descriptor of that directory, which is used as a pointer to keep track
of whether it has been closed and such. It also interprets a nil-pointer as
"relative to the current directory" (it uses AT_FDCWD). I could, of course,
also use the zero-value of that struct for that (in fact, I do as well),
but as there is a meaningful way to interpret a nil-pointer, there's no
harm in doing so as well.

In general, it's of course never *necessary* to interpret a nil-pointer a
specific way. But it does sometimes make things easier to express or nicer
to use.

BTW, as far as slices are concerned: They behave strikingly similar to
maps, as far as the zero-value is concerned - in that all read-operations
work just fine on both a nil-map and a nil-slice, it's just that
write-operations panic (and again, in both cases). The main difference
between them is that *non*-nil maps behave very differently. We don't tend
to notice the "uselessness" of nil-slices in general, though, because we
tend to either assume a certain size for them (in which case they can't be
nil) or we check the length beforehand (just like checking if a map is nil)
when writing to them. i.e. the read-operations are far more common with
slices and we find the idea of "checking" their nil-ness via ranging over
them or explicitly checking their len somewhat more natural.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfHAfA97soJy1iXea1H7Bkv_VO%3D43cLY96zi%2BZ7R0a%3DbTQ%40mail.gmail.com.

Reply via email to