Go's static typing, zero values and lack of implicit conversion shape every line you write.
Go has two ways to declare a variable:
var count intdeclares with an explicit type;var name = "Ann"infers it.varworks at package level and inside functions.count := 0is the short declaration, inferring the type. It only works inside functions and is what you'll use most of the time.
Every variable starts at its zero value — there is no "uninitialized" state. Numbers are 0, bool is false, string is "", and pointers, slices, maps, channels, functions and interfaces are nil. Good Go types are designed so the zero value is useful.
The basic types:
int,int8…int64,uint,uint8…uint64.intis 64 bits on all common platforms; use it unless you need a specific size.float64(prefer it) andfloat32;complex128.bool,string, plus aliasesbyte(=uint8) andrune(=int32, a Unicode code point).
Go performs no implicit conversions, even between int and int64 or int and float64. You convert explicitly with T(x): float64(n) / 2. Converting a float to an int truncates toward zero.
:= needs at least one new variable on its left. In an inner block it creates a new variable that shadows the outer one — a classic source of bugs when you meant to assign with =.
Use fmt.Printf("%T %v\n", x, x) to print a value's type and value while you experiment.
Example
package main
import "fmt"
func main() {
var total int // zero value: 0
price := 2.5 // float64
qty := 3 // int
name, ok := "tea", true
total = int(price * float64(qty)) // explicit conversions
fmt.Println(total, name, ok) // 7 tea true
var s string
fmt.Printf("%q %T\n", s, qty) // "" int
}Remember
:=inside functions,varwhen you need the zero value or package scope- Every type has a usable zero value; nothing is uninitialised
- No implicit numeric conversions — write
float64(n)
Watch out for
- Accidentally shadowing a variable with
:=inside anifor loop block.