golang: invalid operation: someVar == “” (mismatched types *string and string)

This article was published 5 years ago. Due to the rapidly evolving world of technology, some concepts may no longer be applicable.

I was trying to see if a value was empty in a golang script I was writing, when I came across an odd error message:

invalid operation: someVar == "" (mismatched types *string and string)

It turns out that the following code doesn’t return a simple string, but an instance of flag.String

someVar := flag.String("somevar", "", "this is a random flag")

To perform the comparison, you need to use a pointer to it as follows:

if *someVar != "" {
    // Do this
}

Thoughts on this post

Leave a comment?