Go Syntax

Learn the basic structure every Go program follows, including the package declaration, func main, and how semicolons work behind the scenes.

Basic Structure of a Go Program

Every Go file begins with a package declaration, which tells the compiler which package the file belongs to. Files meant to be run directly must declare package main.

Minimal Program Structure

package main

import "fmt"

func main() {
    fmt.Println("Structure matters in Go")
}

The func main Entry Point

When you run a Go program, execution always starts inside func main. There can be only one main function per package main, and it takes no arguments and returns no value.

  • Go is case-sensitive: Main and main are different identifiers
  • Curly braces { } are required around function and block bodies
  • Conditions in if and for statements are not wrapped in parentheses
  • The opening curly brace must stay on the same line as the statement above it

A Function with a Condition

package main

import "fmt"

func main() {
    hour := 14
    if hour < 18 {
        fmt.Println("Good afternoon")
    }
}

Semicolons in Go

Go's grammar technically requires a semicolon at the end of every statement, just like C or Java. However, the Go compiler's lexer automatically inserts these semicolons for you at the end of each line, so you almost never type one yourself.

Note: Because semicolons are inserted automatically after a line's last token, an opening brace { can never go on its own line after a function or if statement — the compiler would insert a semicolon before it and your code would fail to compile.

Correct vs. Incorrect Brace Placement

package main

import "fmt"

func main() {
    // Correct: brace stays on the same line
    fmt.Println("This compiles fine")
}

// The following would NOT compile if written as:
// func main()
// {
//     fmt.Println("broken")
// }
RuleDetail
Case sensitivitymain and Main are different names
BracesRequired for every function, if, and for body
SemicolonsInserted automatically at line end; rarely typed manually
Opening braceMust be on the same line as its statement
Note: gofmt, Go's built-in formatting tool, will automatically arrange your braces and spacing correctly, so you rarely have to think about these rules once you start using it.

Exercise: Go Syntax

Do you need to manually type a semicolon at the end of each Go statement?