Explain it simply
Data types, simply
Go is statically typed, so the compiler must know in advance what kind of data each variable holds. A type is that kind: a whole number, a decimal number, text, or true/false.
It is like a shop cabinet with separate drawers: you do not put shoes in the cash drawer. Go likewise never mixes a value from the int drawer with one from the float64 drawer on its own; to mix them you write 'convert this value to that type' yourself. Once these basic types make sense, writing functions, structs, slices and maps becomes much easier.
Problem → Why → Solution
The problem: you cannot mix numbers and strings, or ints and floats
To total an order you multiply a quantity `age` (an int) by a `price` (a float64) and join the result to a text label. JavaScript would quietly accept this, but the Go compiler rejects both lines, and the program never even starts.
age := 25
price := 19.99
total := age * price // invalid operation: age * price
// (mismatched types int and float64)
label := "Age: " + age // invalid operation: "Age: " + age
// (mismatched types untyped string and int)Why Go refuses to convert automatically
Go has no implicit conversions at all. Turning an int into a float64, losing the fraction when a float becomes an int, turning a number into text: each is a decision that can change meaning, so the compiler makes you choose instead of guessing. Write `float64(age) * price` and `"Age: " + strconv.Itoa(age)`, and anyone reading the code can see exactly what happens.
Core concept: the basic types and conversions
| Type | Holds | Zero value |
|---|---|---|
| bool | true or false | false |
| string | Immutable UTF-8 bytes | "" |
| int, int8 ... int64 | Signed whole numbers | 0 |
| uint, uint8 ... uint64 | Unsigned whole numbers | 0 |
| byte (= uint8) | One byte | 0 |
| rune (= int32) | One Unicode code point | 0 |
| float32, float64 | Floating-point numbers | 0 |
When you use `:=` without a type, Go picks a default from the literal: `25` is `int`, `19.99` is `float64`, `'T'` is `rune` and `"Go"` is `string`. The size of `int` depends on the platform and is 64 bits on 64-bit machines. Use `int` for ordinary whole numbers and `float64` for decimals, and reach for sized types such as `int32` or `uint8` only when a file format or network protocol demands them.
To change a value's type, write `T(v)`: `float64(age)`, `int(price)`. Converting a float variable to an int drops the fraction, truncating toward zero, so with `price` holding 19.99, `int(price)` is `19`; it does not round. (Converting the constant directly, as in `int(19.99)`, is a compile error because the fraction would be lost.) Dividing two integers also gives an integer, so `7 / 2` is `3`.
Between strings and numbers, `T(v)` is the wrong tool; use the `strconv` package. `strconv.Itoa(65)` returns `"65"`, and `strconv.Atoi("65")` returns a number and an error, because the text might not be a number. Writing `string(65)` gives you `"A"`, the character with code point 65, not `"65"`.
Strings are immutable: once created, their bytes cannot be changed. Writing `s[0] = 'G'` is the compile error `cannot assign to s[0] (neither addressable nor a map index expression)`. To change text you build a new string, either with a function such as `strings.ToUpper` or by converting to `[]byte(s)` or `[]rune(s)`, editing that, and converting back with `string(...)`. Comparing two strings with `==` compares their contents byte by byte.
- Check both values' types
- Same type: calculate directly
- Number to number: convert with T(v)
- String and number: use strconv
Go never changes a type behind your back; every conversion is visible in the code.
General pattern: declaring types and converting
var name Type = value // explicit type
inferred := literal // default type from the literal
converted := TargetType(value) // number <-> number
text := strconv.Itoa(number) // int -> string
number, err := strconv.Atoi(text) // string -> int (may fail)
const untyped = 10 // adapts to the context
const typed Type = 10 // always TypeUse `TargetType(value)` between number types and `strconv` between strings and ints. `Atoi` also returns an error, which you must always check. A constant declared without a type is untyped and adapts to wherever it is used.
Example: inspecting types with %T and converting
The `%T` verb prints a value's type. This program shows the type of six variables and then multiplies an int by a float64. Predict what `%T` prints for `initial`, a rune; if you guessed `rune`, there is something to learn here.
package main
import "fmt"
func main() {
age := 25
price := 19.99
name := "ThutaTech"
active := true
initial := 'T'
var level uint8 = 255
fmt.Printf("age: %T\n", age)
fmt.Printf("price: %T\n", price)
fmt.Printf("name: %T\n", name)
fmt.Printf("active: %T\n", active)
fmt.Printf("initial: %T %v %c\n", initial, initial, initial)
fmt.Printf("level: %T %d\n", level, level)
total := float64(age) * price
fmt.Printf("total: %.2f\n", total)
}Code breakdown
- Default types
price := 19.99A literal with a decimal point gets the default type `float64`; `age := 25` becomes an `int`.
- A rune is an int32
fmt.Printf("initial: %T %v %c\n", initial, initial, initial)`rune` is an alias for `int32`, so `%T` prints `int32`. `%v` shows the number `84`, T's code point, and `%c` shows the character `T`.
- A sized type
var level uint8 = 255`uint8` holds only 0 to 255; assigning `256` is a constant overflow and a compile error. `byte` is this same `uint8`.
- Explicit conversion
total := float64(age) * price`age` is converted to `float64` before multiplying by `price`, so both sides match. Without the conversion you get `mismatched types int and float64`.
- Rounding only for display
fmt.Printf("total: %.2f\n", total)`%.2f` only formats the output with two decimals; it does not change `total`. Because of float64's binary representation the stored value may not be exactly 499.75, but it prints as `499.75`.
age: int
price: float64
name: string
active: bool
initial: int32 84 T
level: uint8 255
total: 499.75Strings, bytes and runes
A Go string is a sequence of UTF-8 bytes. `len(s)` returns the number of bytes, not characters. English letters take one byte each, so you never notice, but each Myanmar code point takes three bytes in UTF-8. `s[0]` gives you a byte (`uint8`), while looping over a string with `for range` gives you one rune at a time. Count code points with `utf8.RuneCountInString`.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
word := "Go"
greeting := "မင်္ဂလာပါ"
fmt.Println(len(word), utf8.RuneCountInString(word))
fmt.Println(len(greeting), utf8.RuneCountInString(greeting))
fmt.Println(word[0], string(word[0]))
var small int8 = 126
for range 3 { // range over an int: Go 1.22 and later
small++
fmt.Println(small)
}
}This prints `2 2`, `27 9` and `71 G`, then `127`, `-128` and `-127`. "မင်္ဂလာပါ" has 9 code points and takes 27 bytes. The last part is integer overflow: when an `int8` passes its maximum of 127 at run time, it silently wraps around to -128 with no error. `for range 3` ranges over an integer, available in Go 1.22 and later, to repeat a block three times.
Typed and untyped constants
A constant declared without a type, such as `const limit = 10`, is untyped. It takes on whatever type its context needs, so it can multiply a `float64` or be added to an `int`. `const maxUsers int = 10` is a typed constant: like a variable it is always an `int` and needs a conversion to mix with a `float64`. The compiler evaluates untyped constants with high precision, so large intermediate values such as `1 << 40` are fine.
package main
import "fmt"
const limit = 10 // untyped: adapts to where it is used
const maxUsers int = 10 // typed: always an int
func main() {
ratio := 2.5
fmt.Println(ratio * limit) // limit acts as a float64
fmt.Println(float64(maxUsers) * ratio) // typed: convert first
fmt.Println((1 << 40) / (1 << 30)) // exact constant arithmetic
}It prints `25`, `25` and `1024`. Remove the `float64(...)` on the second line and you get a `mismatched types float64 and int` compile error.
In real projects
Choosing types in real projects
Money calculations avoid float64. Even adding two float64 variables holding 0.1 and 0.2 prints `0.30000000000000004` because of binary floating point, so production systems store amounts as `int64` in the smallest unit, such as cents or pya, or use a decimal library. `int64` is common for database IDs and file sizes, and `[]byte` for binary data and network buffers.
User input and URL query parameters always arrive as strings, so backend code calls `strconv.Atoi` and `strconv.ParseFloat` almost daily. Ignore the error and an input like "abc" silently becomes zero, producing wrong orders. In apps that handle Myanmar text, a rule such as a username length limit should count runes rather than use `len`, which is much closer to the number of characters a user sees.
Common mistakes
Common data type mistakes
1. Converting a number to text with string(n)
`string(65)` is `"A"`, not `"65"`, because the integer is taken as a code point; `go vet` even warns 'conversion from int to string yields a string of one rune'. To get the digits as text, use `strconv.Itoa(n)` or `fmt.Sprint(n)`.
2. Treating len() as a character count
`len("မင်္ဂလာပါ")` is 27, not 9, because it counts bytes. Slicing Myanmar text by byte index, as in `s[:10]`, can cut a character in half and produce invalid UTF-8. Count code points with `utf8.RuneCountInString` and slice through `[]rune(s)`.
3. Throwing away Atoi's error with `_`
With `qty, _ := strconv.Atoi(input)`, a bad input leaves `qty` at 0 and the program carries on without a word. Always check `if err != nil` and report the problem to the user.
4. Storing money in a float64
Floating point cannot store some decimals exactly, so fractions of a cent drift in as you add and subtract. Keep amounts as integer cents and format them only for display, for example with `%d.%02d`.
Mini challenge
Mini challenge: a correctly typed receipt
Store the price of tea in cents, convert a quantity that arrives as text into a number, and print a receipt.
- Use `item := "လက်ဖက်ရည်"`, `qtyText := "3"` and `priceCents := 125`
- Convert the quantity with `strconv.Atoi` and check the error with `if err != nil`
- Print both the rune count and the byte count of the item name
- Show the total as `$3.75`, plus one line built with `strconv.Itoa` giving the cents as text
package main
import "fmt" // TODO: group this with strconv and unicode/utf8
func main() {
item := "လက်ဖက်ရည်"
qtyText := "3"
priceCents := 125
// TODO: qty, err := ... convert qtyText; on error print it and return
// TODO: totalCents := ...
// TODO: print the item, its rune count and its byte count
// TODO: print "total: $D.CC" using / and % on totalCents
// TODO: print "as text: <cents> cents" using strconv.Itoa and +
}Expected: item: လက်ဖက်ရည် runes: 9 bytes: 27 total: $3.75 as text: 375 cents
Show hint
`totalCents/100` is the dollars and `totalCents%100` the cents. `%02d` pads the cents to two digits, so 5 cents shows as `05`. Remember to add `strconv` and `unicode/utf8` to the imports, and to use every package you import.
Show solution
package main
import (
"fmt"
"strconv"
"unicode/utf8"
)
func main() {
item := "လက်ဖက်ရည်"
qtyText := "3"
priceCents := 125
qty, err := strconv.Atoi(qtyText)
if err != nil {
fmt.Println("bad quantity:", err)
return
}
totalCents := qty * priceCents
runes := utf8.RuneCountInString(item)
fmt.Println("item:", item, "runes:", runes, "bytes:", len(item))
fmt.Printf("total: $%d.%02d\n", totalCents/100, totalCents%100)
fmt.Println("as text: " + strconv.Itoa(totalCents) + " cents")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Literals default to int, float64, rune (= int32) and string; byte is another name for uint8.
- Go has no implicit conversions: convert between number types with T(v); float to int truncates.
- Use strconv between strings and numbers; string(n) gives a single character.
- len(s) counts bytes; count Myanmar characters with utf8.RuneCountInString.
- Untyped constants adapt to their context; typed constants keep their one type.
A Tour of Go — Go