Go: Introduction to Go and Installation
Go is a compiled concurrent language developed at Google—it solves engineering problems with minimal syntax, making "fast and simple" a reality.
This tutorial is designed for beginners with no prior experience. It starts with the basics—"What is Go?"—and guides you all the way to writing and running your first command-line tool in Go. Go is the de facto standard in cloud-native (Docker/Kubernetes), microservices, and CLI tools, and is used by over 3 million developers worldwide.
1. What You'll Learn
- What is Go? Who created it, and what problems does it solve?
- Key Differences Between Go and Python, Java, and C++
- Go's Three Design Philosophies (Simplicity, Concurrency, Speed)
- Install Go 1.22+ on Windows, macOS, or Linux
- Write your first "Hello World" program
go run/go build/go fmt—The Three Basic Commands- Plant the
go mod initdependency management seed (Lesson 8: In-Depth)
2. A True Story of a Backend Engineer
(1) Pain Point: The Python API crashes under concurrent load
Alice is a واجهة خلفية engineer, and the API service she wrote in Python has recently been experiencing issues:
"During the online حدث, we received 10,000 concurrent requests, causing API استجابة times to skyrocket from 100 ms to 8 seconds and CPU usage to reach 95%. The service nearly crashed."
After reviewing the واجهة خلفية logs, she discovered that:
- GIL Global Lock: Python's
threadingmodule cannot truly take advantage of multi-core CPUs - Asynchronous Complexity:
asyncioSteep learning curve, poor code readability - Memory Spike: Each طلب uses 50 MB; with 10,000 concurrent requests, 500 GB of memory is used up
- Slow process switching: Switching to
multiprocessingresults in slow startup and high communication overhead
Her boss asked her, "Can we switch to a different programming language?" After doing some research, Alice set her sights on Go.
(2) The Go Solution
Here's how Alice rewrote the same business logic in Go:
// main.go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Performance Comparison (10,000 concurrent users for the same business scenario):
| Dimension | Python Flask | Go net/http |
|---|---|---|
| Average Response Time | 2,500 ms | 45 ms |
| Memory Usage | 500GB | 1.2GB |
| CPU Utilization | Single-core 95% | Multi-core 70% |
| Startup Time | 5s | 20ms |
| Deployment Method | Requires Python Runtime | Single Binary |
(3) Benefits: Why Is Go Worth Learning?
After completing this lesson, you’ll take your first step:
- Understanding the Design Philosophy Behind Go: Know what pain points Go addresses to avoid blindly following trends
- Set up your development environment: Choose from Windows, macOS, or Linux—it only takes 10 minutes.
- Getting "Hello World" to Run: The moment you see
Hello, World!'s output, you've got the hang of it. - Master 3 core commands:
go run/go build/go fmt— enough for everyday development
3. What Is Go?
Go (also known as Golang) is an open-source, compiled language created in 2009 and designed by Google’s Robert Griesemer, Rob Pike, and Ken Thompson. All three are core contributors to the C language and Unix.
(1) The Motivation Behind the Creation of Go
In 2007, Google faced an internal problem:
- C++ compiles too slowly: A full compilation of a large C++ project takes 45 minutes
- Chaotic dependency management: A nightmare of header file inclusions—changing a single line of code affects the entire project
- Challenges in Concurrent Programming: Writing concurrent code with pthreads results in many bugs and is difficult to debug.
- Large team size: With tens of thousands of engineers collaborating, it is difficult to standardize coding styles.
Go's goal: to solve engineering problems with minimal syntax, making collaboration among large teams as smooth as it is in small teams.
(2) Go's Three Major Design Philosophies
graph TB
A[Go Design Philosophy] --> B[Simplicity]
A --> C[Concurrency]
A --> D[Speed]
B --> B1[25 keywords<br/>No inheritance/No issues]
B --> B2[gofmt standard format<br/>No style debates in team code]
C --> C1[goroutine<br/>2KB stack, start 1μs]
C --> C2[channel<br/>CSP concurrency model]
D --> D1[Compiled<br/>Compilation in seconds, 20ms start]
D --> D2[Static link<br/>Single binary deployment]
(3) Typical Areas of Application for Go
| Field | Representative Projects | Why Choose Go |
|---|---|---|
| Cloud-native | Docker, Kubernetes, Istio | Single binary, cross-platform compilation, low memory |
| Microservices | Uber, Twitch, Dropbox | High concurrency, built-in HTTP, comprehensive standard library |
| CLI Tools | gh (GitHub CLI), hugo, cobra | Fast compilation, cross-platform, single-file distribution |
| Databases | TiDB, CockroachDB, InfluxDB | High performance, well-optimized garbage collection |
| DevOps | Terraform, Prometheus, Consul | Concurrently processing millions of metrics |
4. Differences Between Go and Other Languages
(1) Understanding Language Localization at a Glance
graph TB
subgraph L[Division of Labor Among Programming Languages]
direction TB
G[Go<br/>Back-end Services/Cloud-native/CLI]
P[Python<br/>Data Science/AI/Script]
J[Java<br/>Enterprise-level/Android/Big Data]
C[C++<br/>Games/System Software/Embedded]
R[Rust<br/>System-level/Embedded/Security-sensitive]
end
(2) Go vs. Python vs. Java vs. C++
| Dimension | Go | Python | Java | C++ |
|---|---|---|---|---|
| Type System | Static, strongly typed | Dynamic, strongly typed | Static, strongly typed | Static, strongly typed |
| Compilation | Compiled (seconds) | Interpreted | Compiled (slower) | Compiled (very slow) |
| Concurrency Model | goroutine (lightweight) | thread (GIL-limited) | thread | thread |
| Memory Usage | Low (1–2 MB) | High (50–200 MB) | High (100–500 MB) | Medium (10–50 MB) |
| Learning Curve | Gentle | Easiest | Steep | Very Steep |
| Deployment | Single binary | Runtime required | JRE required | Compiled output required |
| Typical Scenarios | Backend/Cloud-Native | Data Science/AI | Enterprise Applications | System Software |
(3) You Should Also Be Aware of Go's "Weaknesses"
- Generics have a short history: Go didn't add generics until version 1.18, which makes it difficult for maintainers of legacy projects
- Verbose error handling:
if err != nil { return err }Writing this 100 times is the norm - No try/catch exception handling: Rely on
errorreturn values andpanic/recover - Relatively new ecosystem: Library quality varies widely; in some fields, Python or Java is a safer choice
5. Install Go
(1) Download Link
Official download link: https://go.dev/dl/
| Platform | Installer | Size |
|---|---|---|
| Windows | go1.22.x.windows-amd64.msi |
~150MB |
| macOS (Intel) | go1.22.x.darwin-amd64.pkg |
~150MB |
| macOS (Apple Silicon) | go1.22.x.darwin-arm64.pkg |
~150MB |
| Linux x86_64 | go1.22.x.linux-amd64.tar.gz |
~70MB |
| Linux ARM64 | go1.22.x.linux-arm64.tar.gz |
~70MB |
▶ Example: Graphical Installation of Go on Windows
# Steps 1: Double-click go1.22.x.windows-amd64.msi
# Steps 2: All the Way Next (Installed by default to C:\Program Files\Go)
# Steps 3: Check the box "Add Go to PATH" (Automatically Configure Environment Variables)
# Steps 4: Finish
# Steps 5: Verify Installation
go version
Output:
go version go1.22.x windows/amd64
▶ Example: Installing Homebrew on macOS
# Steps 1: Install Homebrew (If you haven't installed it yet)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Steps 2: Installation Go
brew install go
# Steps 3: Verification
go version
Output:
go version go1.22.x darwin/arm64
▶ Example: Manual extraction and installation on Linux
# Steps 1: Download (Using 1.22.x as an example)
wget https://go.dev/dl/go1.22.x.linux-amd64.tar.gz
# Steps 2: Extract to /usr/local
sudo tar -C /usr/local -xzf go1.22.x.linux-amd64.tar.gz
# Steps 3: Configure PATH (Write to ~/.bashrc or ~/.zshrc)
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
# Steps 4: Verification
go version
Output:
go version go1.22.x linux/amd64
(5) Verify Environment Variables
| Variable | Meaning | Default Value |
|---|---|---|
GOROOT |
Go installation directory | /usr/local/go (Linux) / C:\Program Files\Go (Win) |
GOPATH |
Workspace Directory | ~/go |
PATH |
Executable file path | Should include $GOROOT/bin |
6. The First "Hello World" Program
(1) Create a working directory
mkdir hello-go
cd hello-go
(2) Write main.go
# At hello-go, create a file in the directory
cat > main.go << 'EOF'
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
fmt.Println("Welcome to Go programming!")
}
EOF
▶ Example: go run Run directly (during development)
go run main.go
Output:
Hello, World!
Welcome to Go programming!
go run will compile and run, but does not save the binary file; it is suitable for development and debugging.
▶ Example: go build Compile to binary (production deployment)
go build -o hello main.go
# Run the generated binary
./hello # Linux/macOS
hello.exe # Windows
go build Generates a single executable file that can be copied directly to any server with the same architecture and run without installing the Go runtime.
▶ Example: gofmt Auto-format code
# Format all .go files in the current directory
gofmt -w .
# Check that the format is correct (do not modify)
gofmt -l .
gofmt is the Go team's "code style police"—all Go code must pass the gofmt check, with no room for style debates.
7. go mod init: Laying the Groundwork for Dependency Management
Comprehensive dependency management is covered in depth in Lesson 8: errors-packages. Here, we’ll lay the groundwork so you understand what a
go.modfile is.
(1) Why is dependency management necessary?
Suppose your project uses a third-party library. How do you declare it? How do you upgrade it? How do you ensure that all team members are using the same version?
Go's answer: go.mod file + go mod command.
▶ Example: go mod init Create a project
# Run the following command in the project's root directory
cd hello-go
go mod init hello-go
Output:
go: creating new go.mod: module hello-go
go: now you can use 'go get' to add dependencies
Generated go.mod file:
module hello-go
go 1.22
(3) What these two lines of code mean
| Field | Meaning |
|---|---|
module hello-go |
Module Name (We recommend using the project domain name in reverse; this tutorial uses the project name) |
go 1.22 |
Minimum Go version requirement |
go get, go mod tidy, and go.sum to integrate third-party libraries (such as gin and gorm) into your project.
8. Complete Example: Your First Go Command-Line Tool
Let's put all of the above knowledge together to write a simple Personal Information Card CLI tool.
# Steps 1: Create a project directory
mkdir my-card && cd my-card
# Steps 2: Initialize module
go mod init my-card
# Steps 3: Write code
cat > main.go << 'EOF'
package main
import "fmt"
func main() {
// Define a variable
name := "Alice"
role := "Backend Engineer"
yearsOfExperience := 5
// Print Card
fmt.Println("========================================")
fmt.Println(" Personal Card CLI")
fmt.Println("========================================")
fmt.Printf("Name: %s\n", name)
fmt.Printf("Role: %s\n", role)
fmt.Printf("Years of Experience: %d\n", yearsOfExperience)
fmt.Printf("Language: Go %s\n", "1.22+")
fmt.Println("========================================")
}
EOF
# Steps 4: Run
go run main.go
# Steps 5: Compile into an executable file
go build -o card main.go
./card
Expected Output:
========================================
Personal Card CLI
========================================
Name: Alice
Role: Backend Engineer
Years of Experience: 5
Language: Go 1.22+
========================================
package main as package Main (Go is case-sensitive). func main() is the program entry point and cannot be renamed.
❓ FAQ
go version reports "command not found" after installation?source ~/.bashrc (or ~/.zshrc). If that still doesn’t work, check whether $GOROOT/bin is included in $PATH: echo $PATH | grep go.mux.HandleFunc("GET /path/{id}", h); (2) for-range integer loops for i := range 10; (3) memory model optimizations. This tutorial is based on Go 1.22 or later.go run and go build?go run = Compile + Run + Clean up intermediate files (for development); go build = Compile only, generate an executable file (for production deployment). go run does not retain the .exe file, while go build does.📖 Summary
- Go is a compiled language released by Google in 2009, designed specifically for large-scale engineering collaboration
- Three Core Design Philosophies: Simplicity (25 keywords + gofmt), Concurrency (goroutines + channels), Speed (compilation in seconds + a single binary)
- Typical use cases: Cloud-native (Docker/K8s), microservices, CLI tools, databases
- Go vs. Python/Java/C++: 30–100x faster performance, 1/30th the memory usage, and native support for concurrency
- Installation: The official download page
go.dev/dlprovides installation packages for Windows, macOS, and Linux. - Three basic commands:
go run(Run) /go build(Compile) /go fmt(Format) go mod initInitialize the module and generate thego.modfile to declare the project metadata
📝 Exercises
-
Basic Exercise (Difficulty ⭐): Install Go 1.22 or later locally, run
go version, and take a screenshot to verify; writehello.goto output "Hello, Go!". -
Advanced Problem (Difficulty ⭐⭐): Extend the Personal Card CLI from above by adding two variables,
city := "Shanghai"andhobby := "Coding", and appending these two lines to the bottom of the card. Finally, compile it into an executable file usinggo build. -
Challenge (Difficulty: ⭐⭐⭐): Research one command-line tool you frequently use (such as
git/docker/kubectl) to see if it’s written in Go. If so, write a 200-character essay explaining “why Go is suitable for CLI tools” (hint: cross-platform compilation, single binary, fast startup).