Bird
Raised Fist0
Goprogramming~15 mins

Writing first Go program - Deep Dive

Choose your learning style10 modes available
Overview - Writing first Go program
What is it?
Writing your first Go program means creating a simple piece of code using the Go language that runs and shows a result. It usually involves writing a small program that prints a message on the screen. This helps you understand how Go code is structured and how to run it. It is the first step to learning how to build software with Go.
Why it matters
This exists to help beginners start coding in Go easily and see immediate results. Without this step, learning Go would feel abstract and confusing, making it hard to understand how code turns into actions on your computer. Writing a first program builds confidence and shows how simple instructions can create useful outcomes.
Where it fits
Before this, you should know what programming is and have a basic idea of how computers follow instructions. After this, you will learn about variables, functions, and how to organize bigger programs in Go.
Mental Model
Core Idea
A Go program is a set of instructions that the computer reads from top to bottom to perform tasks, starting with a main function.
Think of it like...
Writing your first Go program is like writing a recipe for a simple dish, where each step tells the cook exactly what to do in order.
┌─────────────────────────────┐
│ package main                │
├─────────────────────────────┤
│ import "fmt"              │
├─────────────────────────────┤
│ func main() {              │
│     fmt.Println("Hello") │
│ }                         │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Go program structure
🤔
Concept: Learn the basic parts that every Go program needs to run.
A Go program starts with a package declaration, usually 'package main' for executable programs. Then it may import other packages to use extra features. The program runs starting from the 'main' function, which is the entry point.
Result
You know the skeleton of a Go program and where the code starts running.
Understanding the fixed structure helps you organize code so the Go compiler knows what to run first.
2
FoundationPrinting output with fmt package
🤔
Concept: Use the fmt package to show messages on the screen.
The 'fmt' package has functions like Println that print text to the console. You import it with 'import "fmt"' and then call fmt.Println("text") inside main to display messages.
Result
Your program can show messages, making it interactive and visible.
Seeing output is the first way to check if your program works as expected.
3
IntermediateWriting and running your first Go program
🤔Before reading on: Do you think you need to compile Go code before running it, or can you run it directly? Commit to your answer.
Concept: Learn how to write the full code and run it using Go tools.
Create a file named main.go with the code: package main import "fmt" func main() { fmt.Println("Hello, Go!") } Then, open a terminal and run 'go run main.go' to compile and execute the program in one step.
Result
The terminal shows: Hello, Go!
Knowing how to run code immediately helps you test and learn faster without extra steps.
4
IntermediateExploring the main function role
🤔Before reading on: Do you think a Go program can run without a main function? Commit to your answer.
Concept: Understand why main is special and what happens if it is missing.
The main function is the starting point of a Go program. When you run the program, Go looks for main and executes its code. If main is missing, the program will not run and gives an error.
Result
You learn that main is required for executable programs in Go.
Recognizing main as the entry point prevents confusion about why code might not run.
5
AdvancedCompiling vs running Go programs
🤔Before reading on: Does 'go run' create a permanent executable file or just run the code temporarily? Commit to your answer.
Concept: Learn the difference between running code directly and creating a standalone program.
'go run' compiles and runs the program temporarily without saving an executable file. Using 'go build' compiles the code and creates a permanent executable you can run anytime without Go installed.
Result
'go run' shows output immediately; 'go build' creates a file you can run later.
Understanding this helps you choose the right tool for quick tests or building real applications.
6
ExpertHow Go handles program execution internally
🤔Before reading on: Do you think Go compiles code to machine language before running, or interprets it line by line? Commit to your answer.
Concept: Discover what happens inside when you run a Go program.
Go is a compiled language. When you run or build a program, Go compiles your code into machine language specific to your computer. This compiled code runs directly on the processor, making Go programs fast and efficient. The main function is called by the runtime to start execution.
Result
You understand Go programs become fast native code, not interpreted scripts.
Knowing Go compiles to machine code explains why Go programs start quickly and perform well.
Under the Hood
When you run a Go program, the Go compiler translates your human-readable code into machine instructions your computer understands. The runtime system sets up the environment, then calls the main function to start your program. The fmt.Println function writes text to the standard output stream connected to your terminal.
Why designed this way?
Go was designed to be simple, fast, and efficient. Compiling to machine code ensures speed and safety. Having a fixed entry point (main) makes program flow clear. The package system organizes code cleanly. This design avoids complexity found in older languages and supports modern software needs.
┌───────────────┐
│ Go source code│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Go compiler   │
│ (compiles to  │
│ machine code) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Executable    │
│ (runs on CPU) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Runtime calls │
│ main()        │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ fmt.Println() │
│ outputs text  │
└───────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Can you run a Go program without a main function? Commit to yes or no.
Common Belief:Some think Go programs can run without a main function if they have other functions.
Tap to reveal reality
Reality:Go requires a main function in package main to run an executable program.
Why it matters:Without main, the program won't start, causing confusion and errors for beginners.
Quick: Does 'go run' create a permanent executable file? Commit to yes or no.
Common Belief:Many believe 'go run' saves an executable file on disk.
Tap to reveal reality
Reality:'go run' compiles and runs code temporarily without saving an executable.
Why it matters:Expecting a file leads to confusion about where the program is and how to run it later.
Quick: Is Go an interpreted language like Python? Commit to yes or no.
Common Belief:Some think Go runs code line-by-line without compiling.
Tap to reveal reality
Reality:Go compiles code into machine language before running, not interpreting it.
Why it matters:Misunderstanding this can cause wrong expectations about performance and debugging.
Expert Zone
1
The 'package main' and 'func main()' are strictly required only for executable programs, but libraries use different packages and no main function.
2
Go's compilation includes static analysis that catches many errors before running, improving code safety early.
3
The Go runtime manages goroutines and garbage collection even in simple programs, preparing for concurrency and memory safety.
When NOT to use
Writing a first Go program is not suitable when you need scripting or quick prototyping without compilation; in those cases, languages like Python or JavaScript are better.
Production Patterns
In production, the first program pattern scales to larger apps by adding multiple packages, tests, and build scripts, but always starts with a clear main function as the entry point.
Connections
Compiled vs Interpreted Languages
Builds-on
Understanding how Go compiles code helps compare it to interpreted languages like Python, clarifying performance and deployment differences.
Software Build Process
Builds-on
Knowing how Go compiles and links code connects to general software building concepts, useful for managing larger projects.
Recipe Writing in Cooking
Analogy
Seeing a program as a recipe helps grasp the importance of order and clarity in instructions, a concept useful in many planning tasks.
Common Pitfalls
#1Trying to run Go code without a main function.
Wrong approach:package main import "fmt" func greet() { fmt.Println("Hello") } // No main function
Correct approach:package main import "fmt" func main() { fmt.Println("Hello") }
Root cause:Not knowing that main is the required entry point for execution.
#2Expecting 'go run' to create a reusable executable file.
Wrong approach:go run main.go // Then looking for main.exe or similar file
Correct approach:go build main.go // Then run ./main or main.exe
Root cause:Confusing 'go run' with 'go build' commands and their purposes.
#3Writing code without importing fmt but trying to print.
Wrong approach:package main func main() { fmt.Println("Hello") }
Correct approach:package main import "fmt" func main() { fmt.Println("Hello") }
Root cause:Forgetting to import packages needed for functions used.
Key Takeaways
Every Go program starts with a package declaration and a main function as the entry point.
The fmt package is used to print messages to the screen, making programs interactive.
You can run Go programs quickly with 'go run' or create permanent executables with 'go build'.
Go compiles code into fast machine language before running, unlike interpreted languages.
Understanding the structure and execution flow of a Go program is essential for building more complex software.

Practice

(1/5)
1. What is the purpose of the main function in a Go program?
easy
A. It is the starting point where the program begins execution.
B. It defines a package for the program.
C. It imports external libraries.
D. It declares variables for the program.

Solution

  1. Step 1: Understand the role of main function

    The main function is special in Go; it is where the program starts running.
  2. Step 2: Differentiate from other parts

    Packages define code grouping, imports bring libraries, and variables store data, but none start execution.
  3. Final Answer:

    It is the starting point where the program begins execution. -> Option A
  4. Quick Check:

    Program starts at main() -> D [OK]
Hint: Remember: main() is the program's entry point [OK]
Common Mistakes:
  • Confusing package declaration with program start
  • Thinking imports start the program
  • Assuming variables control program flow
2. Which of the following is the correct way to print "Hello, Go!" in a Go program?
easy
A. fmt.Println("Hello, Go!")
B. print("Hello, Go!")
C. fmt.print("Hello, Go!")
D. console.log("Hello, Go!")

Solution

  1. Step 1: Identify the correct print function in Go

    Go uses the fmt package with Println to print with a newline.
  2. Step 2: Check syntax correctness

    fmt.Println("Hello, Go!") is correct; others are either wrong function names or from other languages.
  3. Final Answer:

    fmt.Println("Hello, Go!") -> Option A
  4. Quick Check:

    Use fmt.Println() to print lines in Go [OK]
Hint: Use fmt.Println() for printing with newline [OK]
Common Mistakes:
  • Using fmt.print instead of fmt.Println
  • Using print() which is not standard in Go
  • Using console.log from JavaScript
3. What will be the output of this Go program?
package main
import "fmt"
func main() {
    fmt.Println("Welcome to Go!")
}
medium
A. package main import "fmt" func main() { fmt.Println("Welcome to Go!") }
B. fmt.Println("Welcome to Go!")
C. Welcome to Go!
D. Error: missing main function

Solution

  1. Step 1: Understand program structure

    The program imports fmt and defines main(), which prints the string.
  2. Step 2: Identify output of fmt.Println

    It prints the string exactly: Welcome to Go! with a newline.
  3. Final Answer:

    Welcome to Go! -> Option C
  4. Quick Check:

    fmt.Println prints string output [OK]
Hint: fmt.Println prints the string content, not code [OK]
Common Mistakes:
  • Confusing code with output
  • Expecting code to print itself
  • Thinking main function is missing
4. Identify the error in this Go program:
package main
import "fmt"
func main() {
    fmt.Println("Hello, world!"
}
medium
A. Missing import statement
B. Incorrect function name
C. Missing package declaration
D. Missing closing parenthesis in fmt.Println call

Solution

  1. Step 1: Check syntax of fmt.Println

    The call to fmt.Println is missing a closing parenthesis at the end.
  2. Step 2: Verify other parts

    Package and import are present, function name is correct, so no errors there.
  3. Final Answer:

    Missing closing parenthesis in fmt.Println call -> Option D
  4. Quick Check:

    Check parentheses in function calls [OK]
Hint: Count opening and closing parentheses carefully [OK]
Common Mistakes:
  • Forgetting closing parenthesis in function calls
  • Assuming missing import or package causes this error
  • Misnaming main function
5. You want to write a Go program that prints "Hello" on one line and "World" on the next line. Which code snippet achieves this correctly?
hard
A. package main import "fmt" func main() { fmt.Print("Hello\nWorld") }
B. package main import "fmt" func main() { fmt.Println("Hello") fmt.Println("World") }
C. package main import "fmt" func main() { fmt.Println("Hello\nWorld") }
D. package main import "fmt" func main() { fmt.Print("Hello") fmt.Print("World") }

Solution

  1. Step 1: Understand printing with new lines

    fmt.Println prints text and adds a newline automatically.
  2. Step 2: Check each option's output

    A: Two fmt.Println calls print "Hello" on one line and "World" on the next. Correct.
    B: fmt.Print("Hello\nWorld") prints "Hello\nWorld" (with actual newline) on one line.
    C: fmt.Println("Hello\nWorld") prints "Hello\nWorld" (with actual newline) followed by newline, so output is two lines.
    D: Two fmt.Print calls print "HelloWorld" on one line.
  3. Final Answer:

    package main import "fmt" func main() { fmt.Println("Hello") fmt.Println("World") } -> Option B
  4. Quick Check:

    Use fmt.Println twice for separate lines [OK]
Hint: Use fmt.Println for each line to print separately [OK]
Common Mistakes:
  • Using fmt.Print without newline causes joined output
  • Expecting \n inside fmt.Println to create new line
  • Confusing fmt.Print and fmt.Println behavior
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard