Lesson 2 of 12

Variables & Types

Learn how to declare and constants and which basic types Go provides. Go checks types at compile time but can often infer them for you.

Go
package main

import "fmt"

func main() {
    // Long form: var name type = value
    var name string = "Alice"
    var age int = 30

    // Short form: := infers the type (most common inside functions)
    city := "Paris"
    pi := 3.14159

    // Zero values — Go initializes everything
    var i int       // 0
    var f float64   // 0.0
    var b bool      // false
    var s string    // ""
    fmt.Println(i, f, b, s)

    // Multiple assignment
    x, y := 1, 2
    x, y = y, x  // swap
    fmt.Println(x, y)

    // Constants
    const MaxSize = 1024
    const Pi = 3.14159
    const Greeting = "Hello"

    // iota — auto-incrementing constant
    const (
        Sunday = iota  // 0
        Monday         // 1
        Tuesday        // 2
        Wednesday      // 3
    )

    fmt.Println(name, age, city, pi)
    fmt.Println(Sunday, Monday, Tuesday, Wednesday)
}
Go
package main

import "fmt"

func main() {
    // Basic types
    var i8 int8 = 127         // -128 to 127
    var i32 int32 = 2147483647
    var u64 uint64 = 18446744073709551615
    var f32 float32 = 3.14
    var f64 float64 = 3.141592653589793

    // Type conversion must be explicit
    var x int = 42
    var y float64 = float64(x)  // explicit conversion required
    var z int = int(y)

    // Strings
    s := "Hello, 世界"
    fmt.Println(len(s))         // byte count (not rune count!)
    fmt.Println([]rune(s))      // convert to rune (Unicode codepoints)

    // String concatenation
    first := "Hello"
    second := "World"
    combined := first + ", " + second + "!"
    fmt.Println(combined)

    // Rune (unicode codepoint)
    r := 'A'   // rune (int32)
    fmt.Printf("%c %d\n", r, r)   // A 65

    _ = i8; _ = i32; _ = u64; _ = f32; _ = f64; _ = z  // avoid "declared and not used"
}
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.