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.
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")
// }Exercise: Go Syntax
Do you need to manually type a semicolon at the end of each Go statement?