Go - Syntax & Basics

Beginner 10/10 Teacher 10/10 Architect 10/10

What you’ll learn

  • What package main means and why func main() is the entry point.
  • How import blocks work.
  • Declaring variables and using short declaration :=.

Packages and Imports

package main
import (
    "fmt"
    "math"
)
func main(){ fmt.Println(math.Pi) }

Expected output: 3.141592653589793

Functions

func add(a int, b int) int { return a + b }
func add2(a, b int) int { return a + b }
func split(sum int) (x, y int) { x = sum/2; y = sum-x; return }

Variables

var i int = 42    // explicit type
i := 42          // short declaration (in functions only)
const Pi = 3.14  // constants use const

Key Points

  • Only one loop statement: for.
  • Exported identifiers start with an uppercase letter.
  • Error values are explicit; no exceptions for normal control flow.

Checks for understanding

  1. When can you use := short declaration?
  2. What’s the difference between var and const?
Show answers
  1. Inside functions when declaring a new variable.
  2. var defines a variable whose value can change; const is compile-time constant.

Practice

  • Declare a string with your favorite quote and print its length using len().