The os Package
Start with The os Package
The os package exposes operating-system facilities such as environment variables, files, process arguments and exit status.
What you’ll learn
- Explain the main purpose of the os package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use os.LookupEnv to distinguish an unset environment variable from an explicitly empty one. Use os.CreateTemp and os.Remove for temporary files, or os.Open and os.Stat for existing paths.
OS calls can fail because of permissions, missing files or resource limits. Return or handle their errors rather than assuming every machine has the same paths and configuration.
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"
"os"
)
func main() {
value, exists := os.LookupEnv("GO_COURSE_EXAMPLE_UNSET_9F1")
if exists {
fmt.Println("Configured:", value)
} else {
fmt.Println("Not configured")
}
fmt.Println("Argument count positive:", len(os.Args) > 0)
}
Output
Not configured
Argument count positive: trueTrace what the program does
LookupEnv normally finds no value for the deliberately unusual key. os.Args contains at least the executable name, so its length is positive.
Avoid common mistakes
- Avoid printing environment variables that may contain credentials.
- Error checking is essential for file and process operations.
Try it yourself
Read an environment variable called APP_MODE with LookupEnv and provide a default value when absent.
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 The os Package 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.