Numbers that start with zero

yourbasic.org/golang

What’s up with the counting in this example?

const (
	Century = 100
	Decade  = 010
	Year    = 001
)
// The world's oldest person, Emma Morano, lived for a century,
// two decades and two years.
fmt.Println("She was", Century+2*Decade+2*Year, "years old.")
She was 118 years old.

Answer

010 is a number in base 8, therefore it means 8, not 10.

Integer literals in Go are specified in octal, decimal or hexadecimal. The number 16 can be written as 020, 16 or 0x10.

Literal Base Note
020 8 Starts with 0
16 10 Never starts with 0
0x10 16 Starts with 0x

This bitwise operators cheat sheet covers all bitwise operators and functions in Go.

Zero knowledge (trivia)

There are many ways to write zero in base 8 in Go, including 0, 00 and 000. If you prefer hexadecimal notation, you also have a smörgåsbord of options: such as 0x0, 0x00 and 0x000 (as well as 0X0, 0X00 and 0X000). However, there is no decimal zero integer literal in Go.

In fact, Go doesn’t have any negative decimal literals either: -1 is the unary negation operator followed by the decimal literal 1.

Share this page: