Lesson 1 of 18

Hello, World!

The Anatomy of a Go Program

Every Go source file starts with a package declaration. A package is how Go organizes code: it serves as a namespace, a unit of compilation, and a mechanism for controlling visibility.

The main package is special. It tells the Go compiler that this is an executable program, not a library. Without it, you have a package that other code can import, but nothing you can actually run.

package main

Imports

The import keyword brings other packages into scope. The fmt package (short for "format") handles formatted I/O: printing to the terminal, formatting strings, reading input.

import "fmt"

When you need multiple packages, Go uses a grouped syntax:

import (
    "fmt"
    "math"
    "strings"
)

The Entry Point

Every executable needs a starting point. In Go, that is func main(), with no parameters and no return value. When you run a Go program, execution begins here and here only.

As Captain Picard would say: "Make it so." And with func main(), Go does exactly that.

func main() {
    fmt.Println("Hello, World!")
}

fmt.Println writes its arguments to standard output, followed by a newline character.

Exported Names

Notice the capital P in Println. In Go, any name that starts with an uppercase letter is exported, visible outside its package. A lowercase name is unexported, private to the package.

No public or private keywords. The casing is the access control. This is a deliberate design choice that makes visibility immediately obvious when reading code.

The init() Function

Go has a special function called init() that runs automatically before main(). You never call it yourself --- the runtime calls it for you.

var greeting string

func init() {
    greeting = "Hello from init!"
}

func main() {
    fmt.Println(greeting) // "Hello from init!"
}

Key rules about init():

  • init() takes no arguments and returns nothing
  • A single file can have multiple init() functions --- they run in the order they appear
  • Package-level variables are initialized first, then init() runs, then main()
  • Every package can have init() functions, not just main

The execution order is: package-level variables -> init() -> main().

init() is commonly used for setup that cannot be expressed as a simple variable initialization: validating configuration, registering database drivers, or populating lookup tables.

Your Task

Write a program that prints exactly Hello, World! to standard output.

Go runtime loading...
Loading...
Click "Run" to execute your code.