Golang: Understanding 'null' and nil

Golang doesn't allow NULL (or its version nil) where some languages do allow it.

package main
import "fmt"

func main() {
  someRandom := getString()
  fmt.Println(someRandom)
}

func getString() string {
  return nil // This WON'T compile
}

getString() returns a value. It returns a string. And golang specifies that if you return a value it cannot be nil. (Incidentally, a struct is also a value in golang)

This avoids many NULL pointer errors in other languages.

A NULL pointer error is still possible, however. But only with pointers or references.

package main
import "fmt"

type SomeStruct struct {
  name string
}

func main() {
  s := getSomeStruct()
  fmt.Println(s.name) // It will crash here
}

func getSomeStruct() *SomeStruct {
  return nil // This WILL compile
}

In this case, getSomeStruct() returns a pointer. And so we can return nil.

And if we try to reference the name attribute of the struct we will crash.

Incidentally, a slice is common example of a reference. So you could return nil from a function that returns a slice.

golang
I've removed disqus comments
Instead, press this
to express thanks
So far, 3 people have pressed the octopus