Structure of a Go Program
Start with Structure of a Go Program
Go programs have a predictable shape: a package declaration, optional imports, declarations and functions. Understanding this structure makes later examples much easier to read.
What you’ll learn
- Recognize the main components of a Go source file.
- Distinguish package-level declarations from local statements.
- Understand the role of imports and main().
Understand the idea
package main identifies the package as executable. import "fmt" makes the package available by name. func main() declares the entry-point function. Statements in its braces execute in order.
Go requires a package declaration in every source file. File-scope declarations can appear outside functions, but ordinary short variable declarations cannot appear there. Imports must be used; unused imports cause compilation errors.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
const appName = "Go Explorer"
func main() {
message := "Welcome"
fmt.Println(appName)
fmt.Println(message)
}
Output
Go Explorer
WelcomeTrace what the program does
First, the constant appName is declared at package scope. When the program starts, main() creates a local variable message, prints the application name and then prints the message.
Avoid common mistakes
- A local statement such as
message := "Welcome"belongs inside a function. - Do not expect imports or package declarations to generate output themselves.
Try it yourself
Locate the package declaration, import, constant declaration, function declaration and two function-call statements in the example.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Structure of a Go Program in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.