Puzzle 1 Explanation: Identifiers

Understand the concept of data types in Go.

We'll cover the following

Try it yourself

Try executing the code below to see the outcome.

Press + to interact
package main
import (
"fmt"
)
func main() {
var π = 22 / 7.0
fmt.Println(π)
}

Explanation

There are two surprising things here: one is that π is a valid identifier, and the second is that 22 / 7.0 actually compiles.

Let’s start with π. Go language specification on identifiers says,

Identifiers specify program entities, such as variables and types. An identifier is a sequence of two or more letters and numbers. The first character of an identifier needs to be a letter.

Letters can be Unicode letters, including π. This can be fun to write, but in practice, it’ll make your coworkers’ lives harder. We can easily type π with the Vim editor; however, most editors and IDEs will require more effort.

The only place where Unicode identifiers are helpful is when translating mathematical formulas to code. Besides that, stick to ASCII.

Now to 22 / 7.0. The Go type system will not allow dividing (or any other mathematical operation) between an integer (22) and a float (7.0). But what we have on the right side of the = are constants, not variables. The constant type is defined as it is used; in this example, the compiler converts 22 to a float to complete the operation.

Note: If you first assign 22 and 7.0 to variables and try the same code, it will fail. The following won’t compile.

Press + to interact
package main
import (
"fmt"
)
func main() {
a, b := 22, 7.0
var π = a / b
fmt.Println(π)
}