Variables

Declaration & Initalisation

Declaration

var a, b, c bool

func main() {
	var d int
	fmt.Println(a, b, c, d)
}

Initialise

var a, b, c = true, false, true

func main() {
	var d = 21
	fmt.Println(a, b, c, d)
}

Short Declaration

func main() {
	d := 21
	fmt.Println(d)
}

This requires type inference, and the compiler wont always get it right

func main() {
	a := 1
	b := a / 2
	fmt.Printf("%T %v", b, b)
}

// Output: int 0

Many declarations short hand

var (
	Exported bool       = true
	MaxInt   uint64     = 1<<64 - 1
	z        complex128 = cmplx.Sqrt(-5 + 12i)
)

func main() {
	fmt.Printf("%v %v %v", Exported, MaxInt, z)
}

Constants

Cannot be declared using :=

const (
	name = "ben"
)

func main() {
	const a = 1
}

Casting

T(val) will convert val into type T

func main() {
	a := 1
	b := float32(a) / 2
	fmt.Printf("%v", b)
}