Go Syntax #
A Go file consists of the following key parts:
- Package declaration
- Import packages
- Functions
- Statements and expressions
✅ Example Code #
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}✅ Example Explained #
Line 1: In Go, every program is part of a package. We declare this using the
packagekeyword. In this example, the program belongs to themainpackage.Line 2:
import "fmt"allows us to import functionality from the fmt package.Line 3: A blank line. Go ignores whitespace. Whitespaces make the code more readable.
Line 4:
func main() {}is a function. Any code inside{}is executed when the program runs.Line 5:
fmt.Println()is a function from the fmt package that prints output. Example output:Hello World!
✅ Note: In Go, any executable code belongs in the
mainpackage.
✅ Go Statements #
Example statement:
fmt.Println("Hello World!")👉 In Go, statements are terminated by a newline or a semicolon ;.
- A newline implicitly adds a semicolon.
- Curly brackets
{}should not be placed on a new line by themselves.
Example that works but is not recommended: #
package main
import "fmt"
func main()
{
fmt.Println("Hello World!")
}✅ Compact Code (Not Recommended) #
It’s possible to write very compact Go code, though this reduces readability:
package main; import "fmt"; func main() { fmt.Println("Hello World!"); }✅ Exercises #
Try writing your own simple Go programs using:
- Different print statements
- Simple arithmetic operations
- Defining multiple functions
👉 Experimentation is the best way to get familiar with Go syntax.