The Strict Type System

The Strict Type System in Go: Two travellers put money on a counter. One puts down fifty dollars, the other fifty euros, and they ask the clerk to add it up.

The Analogy: The Exchange Desk at the Border

Two travellers put money on a counter. One puts down fifty dollars, the other fifty euros, and they ask the clerk to add it up. The clerk cannot do it. Not because the arithmetic is hard, but because "one hundred" is not an answer to that question. One hundred what? Any total requires a decision that is not visible in the numbers themselves: which currency the result is in, and at what rate the other one was converted. Somebody has to make that decision on purpose, write it down, and be accountable for the rate they used.

A sloppy exchange desk makes the decision silently. It sees two piles, picks whichever currency the first pile was in, applies yesterday's rate because it was already on the screen, and hands over one hundred and four dollars without comment. The traveller has a number, the number looks plausible, and nothing in the transaction records that a conversion happened at all. When the error surfaces three weeks later in an audit, there is nothing to point at.

Most languages are the sloppy desk when it comes to numbers. Add an integer to a floating point value and the integer is quietly widened. Add a 32 bit value to a 64 bit one and something is promoted. Compare a number to a string and one of them gets coerced by rules written in an appendix. Each individual rule is defensible, and the accumulated effect is that a program contains conversions nobody wrote and nobody can see.

Go is the clerk who refuses. An int and a float64 cannot be added. An int and an int32 cannot be added. Your own Celsius and your own Fahrenheit cannot be added even though both are just float64 underneath, which is the whole point of declaring them. Every conversion is a piece of syntax you typed, sitting in the file where a reviewer can see it and ask whether it was right. The type system is not being pedantic for its own sake, it is refusing to make a decision that belongs to you.


Syntax or Core Structure

Conversion in Go is always written as T(x), and it is always explicit. Named types get the same treatment as built in ones.

package main

import "fmt"

type Celsius float64
type Fahrenheit float64

func toFahrenheit(c Celsius) Fahrenheit {
    return Fahrenheit(c*9/5 + 32)
}

func main() {
    var count int = 42
    var ratio float64 = float64(count) / 5   // the conversion is mandatory
    var small int32 = int32(count)

    body := Celsius(37)

    fmt.Printf("count %d, ratio %.2f, small %d\n", count, ratio, small)
    fmt.Printf("body %.1fC = %.1fF\n", float64(body), float64(toFahrenheit(body)))

    // var wrong float64 = count   // error: cannot use count (int) as float64
    // fmt.Println(body + ratio)   // error: mismatched types Celsius and float64
    fmt.Println("untyped constants adapt:", body+5)

    fmt.Println("int division:", 7/2, "float division:", 7.0/2)
    fmt.Println("truncation:", int(2.9), "and it never rounds")
}

Output:

count 42, ratio 8.40, small 42
body 37.0C = 98.6F
untyped constants adapt: 42
int division: 3 float division: 3.5
truncation: 2 and it never rounds

Two lines in there are the ones people trip over. body+5 compiles because 5 is an untyped constant that becomes a Celsius, while body+ratio does not compile because ratio already committed to being a float64. And 7/2 is 3 because both operands are integers, so the division is integer division; the truncation is not a rounding error, it is the operation you asked for.


Technical Depth: The Types and Their Edges

The Full Numeric Set

TypeSizeRange or note
int8 / uint81 byte-128 to 127 / 0 to 255
int16 / uint162 bytes-32768 to 32767 / 0 to 65535
int32 / uint324 bytesAbout -2.1e9 to 2.1e9 / 0 to 4.3e9
int64 / uint648 bytesAbout -9.2e18 to 9.2e18
int / uintPlatform word8 bytes on every 64 bit target
float324 bytesAbout 7 decimal digits of precision
float648 bytesAbout 15 decimal digits, the default
byte1 byteAn alias for uint8
rune4 bytesAn alias for int32, holds one Unicode code point
uintptrPointer sizeAn integer wide enough to hold an address

byte and rune are true aliases, so byte and uint8 are the same type and are freely interchangeable. int and int64 are not aliases, they are distinct types that happen to be the same width on your machine, and mixing them still requires a conversion. Use int for counts, lengths and indices, and reach for a sized type only when a wire format, a file format or a hardware register demands it.

Overflow Is Silent, and Defined

Signed and unsigned integer overflow in Go wraps around. There is no panic and no error.

var b uint8 = 255
b++                      // b is now 0
var i int8 = 127
i++                      // i is now -128

const overflow int8 = 128   // this one IS a compile error

The distinction matters: constant expressions are checked at compile time, so a literal that does not fit is rejected outright, while a value computed at run time simply wraps. This is why length and count arithmetic should stay in int, and why converting a large int down to an int32 is a decision to make deliberately rather than a formality.

Strings Are Immutable Bytes, Not Characters

A Go string is a read only slice of bytes that conventionally holds UTF-8. That single sentence explains every surprise strings will give you.

s := "caf\u00e9"                       // four characters, five bytes

fmt.Println(len(s))                     // 5, the byte count
fmt.Println(utf8.RuneCountInString(s))  // 4, the character count
fmt.Println(s[3])                       // 195, the first byte of a two byte pair
fmt.Println([]rune(s)[3])               // 233, the code point

// s[0] = 'C'                           // error: strings are immutable
OperationWhat you get
len(s)Number of bytes, never characters
s[i]One byte, which may be half of a character
for i, r := range si is a byte offset, r is a rune
for i := 0; i < len(s); i++Byte by byte iteration, splits multi byte characters
[]byte(s)A copy of the bytes, now mutable
[]rune(s)A copy decoded into code points, four bytes each
string(65)"A", a code point converted to text
strconv.Itoa(65)"65", a number formatted as text

That last pair is a classic bug. string(someInt) does not turn 65 into "65", it treats 65 as a Unicode code point, and modern Go compilers warn about it. Use strconv.Itoa or fmt.Sprintf when you mean formatting.

Because strings are immutable, building one in a loop with += allocates a new string every iteration. strings.Builder exists for that and Module 11 measures the difference.

Named Types Against Aliases

type UserID int      // a new, distinct type
type Ident = int      // an alias: the same type under a second name

A named type is the tool from the analogy: UserID and OrderID can both be int underneath and still refuse to be mixed, which turns an entire class of argument-order bug into a compile error. An alias is a rename with no safety at all, and exists mainly to move a type between packages without breaking callers.

You wantWrite
A number that cannot be confused with other numberstype Cents int64
The same type under a new name during a refactortype Cents = int64
A conversion between related named typesFahrenheit(c*9/5 + 32)
To read the dynamic type out of an interfacev, ok := x.(Cents)

The last row is a type assertion, not a conversion, and it only applies to interface values. Conversions are checked at compile time; assertions are checked at run time and give you the ok form so they need not panic.


Real World Example: Money, Which Is Never a float64

Every payments team learns this lesson once. A price looks like a decimal number, float64 holds decimal numbers, and the resulting system is wrong by a penny in a way that takes a month to find. The type system can prevent it, but only if you use the type system.

package main

import (
    "fmt"
    "strconv"
)

// Cents is a whole number of minor units, so 1999 means 19.99.
type Cents int64

// BasisPoints is a rate: 2000 means 20 percent.
type BasisPoints int64

func format(c Cents) string {
    sign := ""
    if c < 0 {
        sign = "-"
        c = -c
    }
    whole := strconv.FormatInt(int64(c)/100, 10)
    return sign + whole + "." + fmt.Sprintf("%02d", int64(c)%100)
}

func taxOn(amount Cents, rate BasisPoints) Cents {
    // Integer arithmetic throughout, rounded half up by adding 5000
    // before dividing by 10000. No floating point anywhere.
    return Cents((int64(amount)*int64(rate) + 5000) / 10000)
}

func main() {
    var asFloat float64
    for i := 0; i < 100; i++ {
        asFloat += 0.01
    }
    fmt.Println("float64 total:", asFloat)
    fmt.Println("float64 equals 1?", asFloat == 1.0)

    var asCents Cents
    for i := 0; i < 100; i++ {
        asCents += 1
    }
    fmt.Println("cents total:", int64(asCents))
    fmt.Println("cents equals 100?", asCents == 100)
    fmt.Println("formatted:", format(asCents))

    price := Cents(1999)
    tax := taxOn(price, 2000)
    fmt.Println("price", format(price), "tax", format(tax), "due", format(price+tax))

    fmt.Println("untyped constant is fine:", format(price+1))
    // fmt.Println(price + BasisPoints(1))   // error: mismatched types
}

Output:

float64 total: 1.0000000000000007
float64 equals 1? false
cents total: 100
cents equals 100? true
formatted: 1.00
price 19.99 tax 4.00 due 23.99
untyped constant is fine: 20.00

The first two lines are not a Go quirk, they are IEEE-754 arithmetic and every language with binary floating point does the same thing. 0.01 cannot be represented exactly in base two, any more than one third can be written exactly in base ten, so each addition rounds to the nearest representable value and the roundings accumulate. Being wrong by seven parts in ten thousand trillion sounds harmless right up to the moment you compare for equality, or aggregate a million rows, or reconcile against a bank statement that used exact arithmetic.

The integer version is exact because there is nothing to round: a count of pennies is a whole number, and whole numbers are what integers store. This is also why payment APIs and interbank message formats state amounts in minor units, and why a database column for money should be bigint or numeric rather than double precision. If your program never converts an amount to float64, an amount can never drift.

The named types are doing the second half of the work. taxOn(price, 2000) accepts a Cents and a BasisPoints, so swapping the arguments does not compile, and neither does adding a rate to an amount. Both are int64 at run time with exactly zero overhead, and the compiler is enforcing a distinction that exists only in your head otherwise. Note the one deliberate hole: price+1 is legal because 1 is an untyped constant, and it means one penny. Untyped constants keep arithmetic readable, and the cost is that you have to know the unit.

Finally, look at what taxOn had to decide out loud. Integer division truncates, so a rounding policy is not optional, and adding half the divisor before dividing gives round half up. In a real system that policy comes from finance, differs by jurisdiction, and belongs in one function that everything calls, which is easier to arrange when the type system will not let a stray float64 bypass it. int64 cents tops out around ninety thousand trillion units, so the range is never the constraint; the only thing you must choose deliberately is the scale, since some currencies have three decimal places and some instruments are priced to more.


Common Mistakes

  1. Using float64 for money, percentages of money, or anything that must reconcile. Use integer minor units, or a decimal library when you need arbitrary scale. The bug does not appear in testing, it appears in accounting.
  1. Comparing floats with ==. Compare against a tolerance: math.Abs(a-b) < 1e-9. Equality on computed floating point values is almost always a mistake, and NaN is not even equal to itself.
  1. Writing string(count) to format a number. That converts a code point, so 65 becomes "A". Use strconv.Itoa, strconv.FormatInt or fmt.Sprintf.
  1. Assuming len(s) counts characters. It counts bytes. For text that may not be ASCII use utf8.RuneCountInString, and iterate with range rather than by index.
  1. Indexing into a string expecting a character. s[i] is a byte, and for multi byte text it is half of something. []rune(s) gives you real code points at the cost of a copy.
  1. Expecting integer division to round. 7/2 is 3, and int(2.9) is 2. Truncation is the defined behavior; use math.Round or add half the divisor before dividing.
  1. Reaching for int32 or int64 out of habit. Use int for counts and indices. Sized types belong at the boundary where a format demands them, and mixing them elsewhere just fills the code with conversions.
  1. Trusting that a conversion is free of consequences. int32(bigInt) silently keeps the low bits, and float32(preciseValue) silently loses digits. The syntax is explicit so that the loss is visible; do not write it reflexively.
  1. Using an alias when you wanted a named type. type Cents = int64 gives you no protection at all. The version without = is the one that catches bugs.

Best Practices

  • Give domain quantities their own named type: Cents, UserID, Attempts. The safety is free and the signatures become self documenting.
  • Keep money in integer minor units from the wire format to the database, and format it for humans only at the very edge.
  • Use int for lengths, counts and indices, and sized types only where a protocol, file format or hardware interface requires them.
  • Treat every conversion as a claim that the value fits; when it might not, check the range first.
  • Iterate text with range and count characters with utf8.RuneCountInString unless you have proved the input is ASCII.
  • Build strings with strings.Builder in a loop, never with +=.
  • Convert numbers to text with strconv, and reserve fmt.Sprintf for cases where you are formatting more than one thing.
  • Write rounding policy in one function with a name, so that every caller shares it and a reviewer can find it.

Practice Exercises

  1. Reproduce the Drift: Write a program that adds 0.1 to a float64 ten times and prints the total with %v and with %.20f. Explain in a comment why the two outputs differ, then rewrite the accumulation with integers so the result is exact.
  1. Two Types, One Underlying: Define type Meters float64 and type Feet float64, write conversion functions in both directions, and then try to add a Meters to a Feet. Record the compiler error. Add a third function that takes both and returns the total in meters, and note where the conversion had to be written.
  1. Count It Three Ways: Take the string "caf\u00e9 latte" and print len, utf8.RuneCountInString, the result of range iteration collected into a []rune, and the result of a plain index loop. Explain why two of the four disagree with the other two.
  1. A Money Type Worth Shipping: Build a Cents type with functions to parse "19.99" into it, format it back, add two amounts, and apply a rate in basis points with round half up. Include a case that would have been wrong with float64, such as applying 8.25 percent tax to twelve separate line items and comparing the total against the tax on the sum.