Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My explanation for why is the following sentence:

> If a function could fail, the function must return an error as its last return value. The caller should immediately check for errors from that function.

In practice, in idiomatic code it is quite rare for a function that returns a `(* Something, error)` to return `(nil, nil)`, which are the cases where a nil pointer dereference would most often happen. The other case is not _immediately_ checking errors. I would say both of these cases are not idiomatic Go. (Yes, there are exceptions.)

The other cases where I've seen nil dereferences pop up most often:

(1) the zero value for maps is nil, and a nil map is mostly not usable. `m[50] = "foo"` will panic with a nil dereference if you've not initialized `m`. This is one of the most annoying things about Go.

(2) not checking for presence when pulling out of a map. If you have `map[string]* Something` and do `x := m["nonexistent"]` and try to use `x`, it'll blow up. Always use the `x, ok := m["nonexistent"]` form instead, and deal with stuff when `ok == false`.

(3) nil receivers. `var x *Something`, then `x.Method()` -- the `Method()` method _can_ deal when `x == nil`, but most code does not.

My reasons for citing C and Java:

C doesn't have multiple return values, and kinds of C code deals with errors differently. Lots of stuff just returns `NULL` and all too often things don't check for it. (`malloc()` is a perfect example of this -- it rarely fails but a _lot_ of code doesn't check for errors. Now extrapolate that to everything :)

For Java, it's because the try-catch control structure complicates program flow. If you have a large block of code in a try-catch, it is very easy for a different line of code to throw an exception than you expected, and as a result an object you attempt to dereference later is null and you get an NPE. There are ways to deal with this, of course, but in my experience most people are pretty lazy about the non-happy path.

EDIT: formatting. how can a site about programming have such terrible support for typing in code



My 7 years of C++ and 7 yesterday of C# and 5 years of go agree with you. Many more nil pointer exceptions in the former and almost none in the later in similar size (large) codebases.


Most of my experience is in C#, and NullReferenceException is, by far, the most frequent exception that ever happens. Curious about if your experience with it is different, and if it is, how.


Not sure if you're talking to me. I was saying that NullReferenceExceptions happen a lot more in C# than nil pointer panics in Go.


My 6 years of C++ and 8 years of C# and 10 years of Java and 5 years of Go agree with you both.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: