nil detection in Go

Qian Chen picture Qian Chen · Nov 27, 2013 · Viewed 175.8k times · Source

I see a lot of code in Go to detect nil, like this:

if err != nil { 
    // handle the error    
}

however, I have a struct like this:

type Config struct {
    host string  
    port float64
}

and config is an instance of Config, when I do:

if config == nil {
}

there is compile error, saying: cannot convert nil to type Config

Answer

Oleiade picture Oleiade · Nov 27, 2013

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}