liveBook · Manning

Octal literal

As explained in 100 Go Mistakes and How to Avoid Them

An octal integer is an integer literal represented in base 8, traditionally indicated in Go by a leading zero or explicitly by a 0o prefix.

A leading zero changes a Go integer literal to base 8, so 010 means decimal 8 rather than decimal 10. Consequently, 100 + 010 prints 108, a common reading mistake when existing code is treated as decimal. section 3.1

Choose the notation according to whether readability or compatibility with existing code matters:

  • Prefer 0o644 for an explicit octal value; the prefix makes the base immediately visible. section 3.1
  • Use 0644 when matching conventional Linux permission notation, but recognize that the leading zero still means base 8. section 3.1
  • Avoid 0O644 when possible because uppercase O can resemble zero in some fonts. section 3.1

File permissions

Pass an octal literal when opening a file with Linux-style permissions: os.OpenFile("foo", os.O_RDONLY, 0644). For clearer base identification, write the same permission as os.OpenFile("foo", os.O_RDONLY, 0o644). section 3.1

sum := 100 + 010
fmt.Println(sum)

Inspect the minimal expression that exposes the decimal-versus-octal misconception. section 3.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces leading-zero conversion from base 8 to decimal and contrasts conventional 0644 with explicit 0o644 notation.
Examples
Uses 100 + 010, os.OpenFile with 0644, and the equivalent explicit form 0o644.
What you can do after
Apply octal literals in Go arithmetic and os.OpenFile permission arguments while avoiding ambiguous leading-zero readings.
How it connects
Connects octal literals with integer literals, Linux file permissions, os.OpenFile, binary literals, hexadecimal literals, and imaginary literals.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.