Variables and Types
Go is statically typed, meaning every variable has a type known at compile time. The compiler uses this information to catch mistakes early and produce efficient machine code.
Declaring Variables with var
The var keyword declares one or more variables explicitly:
package main
import "fmt"
func main() {
var name string = "Gopher"
var age int = 5
var pi float64 = 3.14159
fmt.Println(name, age, pi)
}You can omit the type when providing an initialiser — Go infers it:
package main
import "fmt"
func main() {
var language = "Go" // inferred as string
var version = 1.23 // inferred as float64
fmt.Println(language, version)
}Short Variable Declaration with :=
Inside a function, := is the idiomatic shorthand for declare-and-initialise:
package main
import "fmt"
func main() {
message := "Hello, Gopher!"
count := 42
ratio := 0.75
fmt.Println(message, count, ratio)
}Idiomatic Go: Prefer
:=inside functions. Reservevarfor package-level variables or when you need to declare a variable without an initial value.
Basic Types
| Category | Types |
|---|---|
| Integer | int, int8, int16, int32, int64 |
| Unsigned | uint, uint8, uint16, uint32, uint64 |
| Float | float32, float64 |
| Complex | complex64, complex128 |
| Boolean | bool |
| String | string |
| Byte / Rune | byte (alias for uint8), rune (alias for int32) |
int and uint are platform-sized (64-bit on 64-bit platforms). Prefer int for general integer work unless you have a specific reason to choose another size.
Zero Values
Every variable in Go is initialised to its zero value if no explicit value is given:
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("int=%d float64=%f bool=%t string=%q\n", i, f, b, s)
// int=0 float64=0.000000 bool=false string=""
}Zero values eliminate the class of bugs caused by uninitialised memory in other languages.
Constants
Use const for values that do not change. Constants are evaluated at compile time:
package main
import "fmt"
const (
MaxRetries = 3
Pi = 3.14159265358979323846
AppName = "learn-go"
)
func main() {
fmt.Println(MaxRetries, Pi, AppName)
}Key Takeaways
- Use
varfor package-level declarations or uninitialisied variables; use:=inside functions. - Every type has a well-defined zero value — Go never leaves memory uninitialised.
intis the default integer type;float64is the default floating-point type.- Constants are declared with
constand evaluated at compile time.