Types and variables
Go is statically typed: every variable has a type the compiler knows, and it never changes. But Go also infers types, so most of the time you don't have to write them. This lesson covers declaring variables, Go's basic types, zero values, constants and conversions.
Declaring variables
package main
import "fmt"
func main() {
var city string = "Pune" // full form
var count = 3 // type inferred: int
price := 19.99 // short form (inside functions): the most common
var ready bool // no value: gets the "zero value", false
a, b := 1, 2 // several at once
a, b = b, a // swap without a temporary variable
fmt.Println(city, count, price, ready, a, b)
fmt.Printf("%T %T %T %T\n", city, count, price, ready)
}Pune 3 19.99 false 2 1 string int float64 bool
:=declares and assigns, inferring the type. It only works inside functions.varworks everywhere (including at package level) and lets you leave out the value.=assigns to an existing variable.
Zero values
There are no uninitialised variables in Go. Every type has a zero value:
package main
import "fmt"
func main() {
var i int
var f float64
var s string
var b bool
var p *int
var list []string
var m map[string]int
fmt.Printf("int %v, float %v, string %q, bool %v\n", i, f, s, b)
fmt.Printf("pointer %v, slice %v (nil? %v), map %v\n", p, list, list == nil, m)
}int 0, float 0, string "", bool false pointer <nil>, slice [] (nil? true), map map[]
Numbers are 0, strings are "", booleans false, and pointers, slices, maps, channels and interfaces are nil. Good Go code designs types so the zero value is useful straight away (an empty strings.Builder or sync.Mutex is ready to use).
Basic types
| Type | Holds | Example |
|---|---|---|
int, int64, int32, int8 |
Signed integers (int is 64-bit on 64-bit systems) |
42 |
uint, uint64, uint8 (byte) |
Unsigned integers | 255 |
float64, float32 |
Decimals (use float64) |
3.14 |
string |
Immutable UTF-8 text | "héllo" |
rune (= int32) |
One Unicode character | 'é' |
bool |
true / false |
true |
complex128 |
Complex numbers | 2+3i |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("int max:", math.MaxInt64)
fmt.Println("int8 range:", math.MinInt8, "to", math.MaxInt8)
fmt.Println("uint8 max:", math.MaxUint8)
var x uint8 = 255
x++
fmt.Println("255 + 1 as uint8 =", x)
a, b := 0.1, 0.2
fmt.Println(a + b)
fmt.Println(0.1 + 0.2) // constants: computed exactly by the compiler
fmt.Println(7/2, 7.0/2, 7%2)
}int max: 9223372036854775807 int8 range: -128 to 127 uint8 max: 255 255 + 1 as uint8 = 0 0.30000000000000004 0.3 3 3.5 1
Integers wrap around when they overflow (no crash, no error), so pick a type big enough. As in every language, 0.1 + 0.2 isn't exactly 0.3 in binary floating point, but when both are constants, the compiler computes the sum exactly before it ever becomes a float64. And integer division drops the remainder.
Strings, bytes and runes
A Go string is a read-only sequence of bytes, usually UTF-8 text. That matters as soon as you leave plain English:
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := "Hello, नमस्ते"
fmt.Println(len(s), "bytes,", utf8.RuneCountInString(s), "characters")
fmt.Println(s[0], string(s[0])) // indexing gives a byte
for i, r := range "héllo" { // range gives runes (characters)
fmt.Printf("%d:%c ", i, r)
}
fmt.Println()
fmt.Println(strings.ToUpper("go"), strings.Contains("golang", "lang"))
fmt.Println(strings.Split("a,b,c", ","), strings.Join([]string{"x", "y"}, "-"))
fmt.Println(strings.TrimSpace(" padded "), strings.Repeat("=", 10))
fmt.Println(strings.Fields(" split on spaces "), strings.ReplaceAll("a-b-c", "-", "+"))
raw := `a raw string: \n stays as is, and "quotes" are fine`
fmt.Println(raw)
}25 bytes, 13 characters 72 H 0:h 1:é 3:l 4:l 5:o GO true [a b c] x-y padded ========== [split on spaces] a+b+c a raw string: \n stays as is, and "quotes" are fine
len(s)counts bytes: Hindi and accented characters take 2–3 bytes each in UTF-8.s[i]is a byte;for i, r := range swalks runes (Unicode characters), with their byte positions.- Strings can't be changed; operations return new strings. To build a long string piece by piece, use
strings.Builder. - Backtick strings are raw: no escapes, and they can span several lines. They're handy for regexes, SQL and JSON.
Conversions are always explicit
Go never converts between types automatically, not even int to float64:
package main
import "fmt"
func main() {
count := 3
price := 19.99
total := float64(count) * price
fmt.Printf("%.2f\n", total)
f := 9.99
fmt.Println(int(f)) // truncates
fmt.Println(string(rune(65))) // a number to a character
var big int64 = 300
fmt.Println(uint8(big)) // wraps: 300 - 256
}59.97 9 A 44
Mixing types without converting is a compile error:
package main
import "fmt"
func main() {
count := 3
price := 19.99
fmt.Println(count * price)
}# command-line-arguments ./main.go:8:14: invalid operation: count * price (mismatched types int and float64)
It feels strict at first, but it removes a whole class of silent bugs (C's signed/unsigned surprises, JavaScript's "5" * 2).
Strings ↔ numbers: strconv
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
fmt.Println(n+1, err)
_, err = strconv.Atoi("42abc")
fmt.Println("error:", err)
f, _ := strconv.ParseFloat("3.75", 64)
b, _ := strconv.ParseBool("true")
fmt.Println(f*2, b)
s := strconv.Itoa(2026) + "-11"
fmt.Println(s, strconv.Quote("hi\n"))
}43 <nil> error: strconv.Atoi: parsing "42abc": invalid syntax 7.5 true 2026-11 "hi\n"
Parsing functions return a value and an error, which you must check. That's Go's error-handling style, covered fully in Error handling. _ throws away a value you don't need.
Constants
package main
import "fmt"
const Pi = 3.14159
const AppName = "shop"
type Weekday int
const (
Sunday Weekday = iota // 0, then counts up
Monday
Tuesday
)
const (
_ = iota
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)
func main() {
fmt.Println(AppName, Pi*2)
fmt.Println(Sunday, Monday, Tuesday)
fmt.Println(KB, MB, GB)
const huge = 1 << 100 // untyped constants can be huge…
fmt.Println(huge >> 98) // …as long as the result fits
}shop 6.28318 0 1 2 1024 1048576 1073741824 4
iota counts 0, 1, 2… within a const ( … ) block, which is how Go makes enums. Constants without a type are "untyped" and very precise until they're used.
Type definitions
You can create your own named types from existing ones. The compiler then keeps them apart:
package main
import "fmt"
type Celsius float64
type Fahrenheit float64
func ToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func main() {
temp := Celsius(21.5)
fmt.Printf("%.1f°C = %.1f°F\n", temp, ToF(temp))
// ToF(Fahrenheit(70)) would not compile: wrong type
}21.5°C = 70.7°F
Named types prevent mix-ups like passing metres where seconds were expected, and you can attach methods to them (see Structs and methods).
Practice
- Declare variables of five different types without values and print their zero values with
%qor%v. - Count the bytes and the characters in a word in your own language.
- Read a number from a string with
strconv.Atoi, handle the error, and print the number doubled. - Define a
type Rupees int64that stores paise, and printRupees(123456)as₹1234.56.
1.What is the value of var n int before you assign anything?
2.Why doesn't count * price compile when count is int and price is float64?
3.What does len("héllo") return?
4.Where can you use x := 5?