Variables and Data Types
What you will learn
This lesson covers how to store values in Go. You will learn the two ways to declare a variable and when to use each, what a zero value is, the handful of types you will use constantly, how constants differ from variables, and why Go makes you convert between number types yourself.
Go is statically typed: every variable has one type, fixed when the program is compiled. It is also strongly typed: Go will not quietly mix types together. These two properties are the source of most of the rules below.
Declaring a variable with var
The var keyword declares a variable. The type comes after the name:
package main
import "fmt"
func main() {
var name string
var age int
var isStudent bool
fmt.Println(name, age, isStudent)
}
This prints 0 false, an empty string, zero, and false. A variable declared without a value starts with a zero value, which is covered in a moment.
You can give it a value at the same time:
var name string = "Alice"
var age int = 25
If you provide a value, you can leave out the type and Go infers it:
var name = "Alice" // string
var age = 25 // int
You can also declare several variables at once:
var i, j int = 1, 2
var golang, python, rust = true, false, "yes"
var works both inside functions and at the top level of a file.
Short declarations with :=
Inside a function, the short form is much more common:
func main() {
name := "Alice"
age := 25
height := 5.8
isStudent := true
fmt.Println(name, age, height, isStudent)
}
:= means "declare these variables and give them the types of the values". Here Go infers string, int, float64, and bool. You can check what it chose with the %T verb:
fmt.Printf("%T %T %T %T\n", name, age, height, isStudent)
// string int float64 bool
:= has two rules worth remembering.
It only works inside functions. At the top level of a file, every declaration must begin with a keyword like var or func:
package main
count := 10 // not allowed here
syntax error: non-declaration statement outside function body
It needs at least one new variable on the left. a := 1 followed by a := 2 is an error (no new variables on left side of :=). To change an existing variable, use plain =:
score := 10
score = 20 // assignment, no colon
Choosing between var and :=
Use := for most local variables, when the value makes the type obvious. Use var when you want the zero value on purpose, when you declare at the top level, or when an explicit type makes the code clearer:
name := "Mira" // short and clear
var retries int // intentionally starts at zero
var timeout time.Duration = 5 * time.Second // explicit type helps here
Zero values
In many languages, a variable you forgot to set contains garbage or null. Go never leaves a variable undefined. Every type has a zero value that it starts with:
| Type | Zero value |
|---|---|
Numbers (int, float64, ...) | 0 |
bool | false |
string | "" (empty string) |
| Pointers, slices, maps, functions, interfaces | nil |
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
// 0 0 false ""
This is a design choice that removes a whole class of bugs. Good Go types are designed so that their zero value is already useful.
The core types
You will use these four constantly:
| Type | Holds | Example |
|---|---|---|
int | Whole numbers | 42, -7 |
float64 | Decimal numbers | 3.14 |
string | Text | "hello" |
bool | true or false | true |
Go also has sized integers (int8, int16, int32, int64), unsigned integers (uint, uint8, ...), and float32. Use plain int and float64 unless you have a specific reason, such as a file format or API that demands a size. Two aliases appear often: byte is uint8, and rune is int32, used for a single Unicode character.
A note on strings
A string holds bytes, and len counts bytes, not characters:
s := "héllo"
fmt.Println(len(s)) // 6, because é takes two bytes
fmt.Println(len([]rune(s))) // 5 characters
Strings cannot be changed once created. Operations like + build a new string.
Type conversion is explicit
Go will not mix types automatically. Adding an int to a float64 is an error:
count := 3
price := 9.50
total := count * price
invalid operation: count * price (mismatched types int and float64)
You convert one side yourself, with the type name used like a function:
total := float64(count) * price // 28.5
Conversion between number types can lose information, which is exactly why Go makes you write it:
f := 3.99
n := int(f) // 3, the decimal part is dropped, not rounded
Converting a number to text needs a function, not a type conversion. Use strconv.Itoa(42) to get "42".
Type inference and untyped constants
When you write x := 42, Go picks the type from the value's form: whole numbers become int, decimals float64, and imaginary numbers complex128. If you assign from another variable, the new one takes that variable's type:
i := 10
j := i // j is an int, like i
A literal like 8 written directly in your code is an untyped constant. It adapts to whatever type needs it, so it can be used as an int in one place and a float64 in another.
Constants
A constant is a value fixed at compile time. Declare it with const:
const Pi = 3.14159
const appName = "tasker"
const (
maxRetries = 3
timeout = 30
)
Constants cannot change, they must be assigned when declared, and := cannot be used with them. They can hold numbers, strings, and booleans.
const x = 10
x = 20 // error: cannot assign to x
Constants shine for fixed values like limits, names, and configuration defaults, because the compiler can check them and they carry a name instead of a magic number.
Common doubts
f := 3.142 // f is float64
f = 8 // works
The literal 8 is an untyped constant, so Go adapts it to float64 and treats it as 8.0. It would also work for a float32 variable.
f := 3.142
n := 8
f = n // cannot use n (variable of type int) as float64 value in assignment
Once you store 8 in n := 8, the variable n has a fixed type, int. A typed value no longer adapts. Convert it with f = float64(n).
Common mistakes
- Declared and not used. Go treats an unused local variable as an error (
declared and not used: count). Use it, or replace it with_if you really must discard a value. - Using
:=at the top level. Usevarthere. - Redeclaring with
:=instead of assigning with=. - Mixing
intandfloat64in arithmetic. Convert one of them explicitly. - Assuming integer division returns a decimal.
7 / 2is3, because both operands are integers.
Practice
Declare an integer count, a floating-point price, and a constant taxRate of 10%. Compute the subtotal and the total with tax, converting types where needed. Print the results with two decimal places.
package main
import "fmt"
func main() {
const taxRate = 0.10
count := 3
price := 9.50
subtotal := float64(count) * price
total := subtotal * (1 + taxRate)
fmt.Printf("Subtotal: %.2f\n", subtotal)
fmt.Printf("Total: %.2f\n", total)
}
Output:
Subtotal: 28.50
Total: 31.35
count is an int and price is a float64, so count must be converted with float64(count) before multiplying. taxRate is an untyped constant, so it adapts to float64 without any conversion. %.2f prints a float with two decimal places.
Summary
Every Go variable has a fixed type and starts with a zero value instead of being undefined. Use := for most local variables and var for zero values, top-level declarations, or explicit types. The core types are int, float64, string, and bool, and conversions between them are always written out, which makes information loss visible. Constants are fixed at compile time and untyped literals adapt to the type they are used with.
Official reference: A Tour of Go: Basics and the Constants section of the specification.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.