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



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:

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:

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:



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:

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

100%
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
💡 Tip: If you've heard of Docker or Kubernetes, their core code is written in Go. Go is the "native language" of the cloud-native era.



4. Differences Between Go and Other Languages

(1) Understanding Language Localization at a Glance

100%
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"

⚠️ Note: Go is not a one-size-fits-all language. Use JavaScript for web front-end development, Python for data analysis, and Kotlin or Swift for mobile development. Go focuses on server-side, CLI, and cloud-native applications.



5. Install Go

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

BASH
# 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:

TEXT
go version go1.22.x windows/amd64

▶ Example: Installing Homebrew on macOS

BASH
# 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:

TEXT
go version go1.22.x darwin/arm64

▶ Example: Manual extraction and installation on Linux

BASH
# 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:

TEXT
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

BASH
mkdir hello-go
cd hello-go

(2) Write main.go

BASH
# 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)

BASH
go run main.go

Output:

TEXT
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)

BASH
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

BASH
# 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.mod file 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

BASH
# Run the following command in the project's root directory
cd hello-go
go mod init hello-go

Output:

TEXT
go: creating new go.mod: module hello-go
go: now you can use 'go get' to add dependencies

Generated go.mod file:

TEXT
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
💡 Tip: In Lesson 8, you’ll learn advanced commands such as 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.

BASH
# 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:

TEXT
========================================
         Personal Card CLI
========================================
Name:               Alice
Role:               Backend Engineer
Years of Experience: 5
Language:           Go 1.22+
========================================
🔥 Common Mistake: Do not write package main as package Main (Go is case-sensitive). func main() is the program entry point and cannot be renamed.


❓ FAQ

Q What is the relationship between Go and Golang?
A The official name of Go is "Go," but since "Go" is too generic and makes it difficult to find information, the community generally uses "Golang" as an alias (the domain golang.org also uses this). The two terms are completely interchangeable; use whichever one you prefer.
Q What is Go best suited for?
A Go’s strengths lie in server-side development: APIs/microservices, CLI tools, cloud-native applications (Docker and K8s are both written in Go), databases, and message queues. Go is not well-suited for desktop GUIs, mobile apps, front-end development, or game engines (other languages are better suited for these areas).
Q How much of a performance difference is there between Go and Python?
A For CPU-intensive tasks, Go is typically 30–100 times faster than Python; for I/O-intensive tasks, it can be 10–50 times faster when using goroutines. The difference stems from: compiled vs. interpreted, goroutines vs. the GIL, and strong-typing optimizations.
Q What should I do if go version reports "command not found" after installation?
A This is usually because the PATH is not configured. On Windows, restart the terminal or log out and back in; on Linux/macOS, run source ~/.bashrc (or ~/.zshrc). If that still doesn’t work, check whether $GOROOT/bin is included in $PATH: echo $PATH | grep go.
Q Are there significant differences between Go 1.22 and earlier versions?
A Go 1.22 introduces three major changes: (1) HTTP routing enhancements 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.
Q Do I need to learn C before learning Go?
A No. One of Go’s design goals is to be “simpler than C++.” As long as you have a basic understanding of any programming language (Python, Java, or JavaScript are all fine), you can start learning Go right away. Go has only 25 keywords, fewer than most languages.
Q What is the difference between go run and go build?
A 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


📝 Exercises

  1. Basic Exercise (Difficulty ⭐): Install Go 1.22 or later locally, run go version, and take a screenshot to verify; write hello.go to output "Hello, Go!".

  2. Advanced Problem (Difficulty ⭐⭐): Extend the Personal Card CLI from above by adding two variables, city := "Shanghai" and hobby := "Coding", and appending these two lines to the bottom of the card. Finally, compile it into an executable file using go build.

  3. 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).

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏