DEV Community

Momchil Atanasov
Momchil Atanasov

Posted on

Go’s true can be false

#go

This is something that not all Go developers are probably aware of. Go allows you to do things like the following.

var true = false
Enter fullscreen mode Exit fullscreen mode

Which also means that the following code compiles and runs.

package main

import "fmt"

var true = false

func main() {
  var status bool = true // This will actually be false.
  if status {
    fmt.Println("True")
  } else {
    fmt.Println("False")
  }
}
Enter fullscreen mode Exit fullscreen mode

And it outputs False.

Even code like this is possible.

package main

import "fmt"

var int = false // Wait, what?!?

func main() {
  var status bool = int // Really?!?
  if status {
    fmt.Println("True")
  } else {
    fmt.Println("False")
  }
}
Enter fullscreen mode Exit fullscreen mode

So it seems that some keywords are actually not keywords in Go. I filed an issue a while back and got the reply that this was by design. Not sure what purpose it serves. If you know, please share in the comments.

I wonder if this will be changed in v2, where backward compatibility could be broken.

In the meantime, this is not something to really worry about. Since all these keywords are lowercase, in practice they are private to the package so it's not possible for a dependency to mess your code up.


NOTE: This post is a more condensed version of an old post of mine.

Top comments (2)

Collapse
 
dogers profile image
Dogers

Go v2 seems less and less likely..
phoronix.com/news/Go-Language-Road...

Collapse
 
mokiat profile image
Momchil Atanasov

Good read, thanks. I guess it makes sense for now, especially since v2 was mostly discussed around generics and now that they managed to introduce them in a backward-compatible way, there is no immediate need for any major changes.

The next big pain point for most developers has to be error handling. It will be interesting to see how the language evolves there.