BeginnerLesson 2 of 15
Variables, Types & Constants – Go
var, :=, zero values, type conversion and const.
Go is statically typed. You declare variables with var or – inside functions – with the short form := (type inference). Uninitialized variables get their zero value (0, "", false, nil).
package main
import "fmt"
func main() {
var name string = "Ada"
var alter int = 36
groesse := 1.68 // float64
aktiv := true
var leer int // zero value: 0
const Pi = 3.14159
fmt.Println(name, alter, groesse, aktiv, leer) // Ada 36 1.68 true 0
fmt.Printf("%T %T %T\n", alter, groesse, aktiv) // int float64 bool
}The most important types: int, float64, string, bool, byte (uint8) and rune (a Unicode character). Go never converts implicitly – you write conversions explicitly. You convert numbers and strings with the strconv package.
package main
import (
"fmt"
"strconv"
)
func main() {
var s string
var b bool
var f float64
var p *int
fmt.Printf("%q %v %v %v\n", s, b, f, p) // "" false 0 <nil>
x, y := 7, 2
fmt.Println(x/y, x%y, float64(x)/float64(y)) // 3 1 3.5
n, err := strconv.Atoi("42")
fmt.Println(n+1, err) // 43 <nil>
text := strconv.Itoa(99) + "!"
fmt.Println(text) // 99!
}Constants declared with const are immutable. With iota you generate consecutive values – Go's typical enumerations (enums):
package main
import "fmt"
type Farbe int
const (
Rot Farbe = iota // 0
Gruen // 1
Blau // 2
)
func main() {
fmt.Println(Rot, Gruen, Blau) // 0 1 2
var c Farbe = Blau
fmt.Println(c == Blau) // true
}WarningInteger division truncates (
7 / 2 = 3), and int + float64 is a compiler error – convert with float64(x). := only works inside functions; at package level you need var.TipWith
x, y = y, x you swap two values without a helper variable. The underscore _ discards a value you do not need, e.g. _, err := f().