V
Vel·ToolKit
Simple · Fast · Ready to use
EN
Chapter 2 of 20

Variables, Constants, Types

var / := / const, basic data types, and zero values

Declaring Variables

Go declares variables with var; inside a function the short declaration := lets the type be inferred.

package main

import "fmt"

func main() {
    var name string = "Alice"
    var age = 30        // type inferred from the literal
    count := 0          // same as var count int = 0
    var x, y int = 1, 2 // multiple variables

    fmt.Println(name, age, count, x, y)
}

Basic Types

  • Integers: int / int8 / int16 / int32 / int64 / uint... / byte (uint8) / rune (int32)
  • Floating point: float32 / float64
  • Complex: complex64 / complex128
  • Boolean: bool (true / false)
  • String: string (an immutable UTF-8 byte sequence)

Zero Values

A variable with no explicit initializer takes its zero value: 0 for numbers, false for bool, "" for string, nil for reference types.

package main

import "fmt"

func main() {
    var n int      // 0
    var s string   // ""
    var b bool     // false
    var p *int     // nil

    fmt.Printf("n=%d s=%q b=%t p=%v\n", n, s, b, p)
}

Constants

const is fixed at compile time and cannot be changed. Combined with iota it can generate enum-like constants.

package main

import "fmt"

const Pi = 3.14159

const (
    Sunday = iota // 0
    Monday        // 1
    Tuesday       // 2
)

func main() {
    fmt.Println(Pi)
    fmt.Println(Sunday, Monday, Tuesday)
}

Type Conversion

Go performs no implicit conversion; you must convert explicitly with T(v):

package main

import "fmt"

func main() {
    i := 42
    f := float64(i)
    u := uint(f)
    fmt.Println(i, f, u)
}