Go Syntax Overview
- A Go source file is generally composed of the following key components:
1.Package Declaration – Defines the package name for the file.
2.Functions – Contains executable code, typically starting with a main() function.
3.Statements and Expressions – The actual instructions and logic written in G.
4.Import Statements – Includes required packages from the Go standard library or external sources.
Example:
// Define the main package
package main
// Import the fmt package for formatted I/O
import "fmt"
// Entry point of the program
func main() {
// Print a message to the console
fmt.Println("Hello, World!")
}
Example explained
Line 1: In Go, every program is part of a package. We define this using the package keyword. In this example, the program belongs to the main package.
Line 2: import ("fmt") lets us import files included in the fmt package.
Line 3: A blank line. Go ignores white space. Having white spaces in code makes it more readable.
Line 4: func main() {} is a function. Any code inside its curly brackets {} will be executed.
Line 5: fmt.Println() is a function made available from the fmt package. It is used to output/print text. In our example it will output "Hello World!".
Note: In Go, any executable code belongs to the main package.
Go Statements
- In Go, a line like fmt.Println("Hello World!") is called a statement.
- Go separates statements either with a semicolon (;) or simply by placing each statement on its own line. When you press Enter at the end of a line, Go automatically inserts a semicolon behind the scenes — even though you don’t see it in your code.
- One important rule in Go: the opening curly brace { must not appear on a new line by itself. It should be placed at the end of the control statement line (like func, if, for, etc.).
- Try running the code below and observe what happens:
Example:
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
Compact Go Code
- You can write Go code in a more condensed format, as shown below. However, this style is generally discouraged since it reduces readability and makes maintenance harder:
Note: While compact code may look cleaner at first glance, it's best to prioritize clarity over brevity.
Example:
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}