patterngoCritical
nil detection in Go
Viewed 0 times
nildetectionstackoverflow
Problem
I see a lot of code in Go to detect nil, like this:
however, I have a struct like this:
and config is an instance of Config, when I do:
there is compile error, saying:
cannot convert nil to type Config
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:
or
or
Then you'll be able to check if
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 nilor
config := &Config{
host: "myhost.com",
port: 22,
} // not nilor
var config *Config // nilThen you'll be able to check if
if config == nil {
// then
}Code Snippets
config := new(Config) // not nilconfig := &Config{
host: "myhost.com",
port: 22,
} // not nilvar config *Config // nilif config == nil {
// then
}Context
Stack Overflow Q#20240179, score: 224
Revisions (0)
No revisions yet.