HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

nil detection in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
nildetectionstackoverflow

Problem

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

Solution

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
}

Code Snippets

config := new(Config) // not nil
config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil
var config *Config // nil
if config == nil {
    // then
}

Context

Stack Overflow Q#20240179, score: 224

Revisions (0)

No revisions yet.