root@coding-prodigies:~# โ–Š
// lesson 2 of 11 ยท 14 min

Syntax and types

โš‘ Report an issue with this lesson
package main

import "fmt"

func main() {
    name := "Ada"      // short variable declaration, type inferred
    var age int = 28
    price := 29.99

    fmt.Printf("%s is %d years old\n", name, age)
}

:= declares and infers the type in one step -- the most common way to create a variable in idiomatic Go. It's shorthand for a var declaration with an inferred type, and it only works inside a function body (package-level variables need the full var form):

var age int = 28   // explicit type
var age2 = 28        // inferred, still var
age3 := 28           // inferred, short form -- equivalent to var age3 = 28

const MaxCourses = 100 // constants use const, never := or var

Go's zero values matter more than in most languages: every variable declared with var and no initializer gets a well-defined default rather than being left uninitialized -- 0 for numeric types, "" for strings, false for bool, and nil for pointers, slices, maps, channels, and interfaces:

var count int      // 0
var name string     // ""
var active bool     // false
var courses []string // nil, but len(courses) is still a safe 0

This is why Go rarely needs a separate "uninitialized" state or an optional type for basic values -- a fresh int is predictably 0, not garbage memory.

Go's basic numeric types come in explicit sizes -- int8/int16/int32/int64 and their unsigned uint... counterparts, plus a platform-sized int that's the default for ordinary integer math. Mixing types in an expression is a compile error, not an implicit conversion, which catches a class of bugs other languages let slide:

var a int32 = 5
var b int64 = 10
// sum := a + b // compile error: mismatched types int32 and int64
sum := int64(a) + b // explicit conversion required

Try it yourself

Exercise: Declare a name string and age int using :=, then print them with fmt.Printf.
Expected output: open-ended โ€” there's no single correct output here, just get your code running without errors.
go
Output

      
    

Run your code and get it working before marking this lesson complete.

// free preview

8 more lessons โ€” including Capstone project: a course catalog CLI โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99