Quickly Master Go: Install, Code, Concurrency, and Testing
Learn how to set up Go in Linux, macOS, and Windows, understand its core syntax, manage packages, work with variables, arrays, slices, maps, control structures, goroutines, channels, interfaces, write unit tests, use Go Convey, connect databases with GORM, and build simple web servers with the standard library or Gin.
Overview
Golang is a favorite in the cloud‑native era because it is simple to learn, enforces clean code, and enables high‑concurrency applications, making it suitable for web back‑ends, databases, cloud‑native services, and blockchain.
Environment Preparation
Install Golang
Linux
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.16.2.linux-amd64.tar.gz export PATH=$PATH:/usr/local/go/bin go versionmacOS
Download the installer package from the official site and run it.
Windows
Download the installer executable and follow the wizard.
Official download page: https://golang.org/dl/
Set GOPATH
GOPATH indicates where third‑party packages are stored locally; adding a convenient directory simplifies dependency management.
IDE Recommendation
GoLand is recommended for its out‑of‑the‑box features and rich plugin ecosystem. Vim users can install the GoLand Vim plugin to combine IDE power with Vim efficiency.
Language Syntax
Package Concept
package main
import "fmt"
func main(){
fmt.Println("niuniumart")
}Every executable Go program must contain a package declaration, import statements, and a function.
Package Management Tools
Three common tools:
GOPATH (go get) – simple but lacks version control.
DEP – vendor‑based packaging used by some large teams.
GoMod – module system that stores dependencies in a versioned cache.
Variable Definition and Initialization
var globalStr string
var globalInt int
func main(){
var localStr string
var localInt int
localStr = "first local"
localInt = 2021
globalInt = 1024
globalStr = "first global"
fmt.Printf("globalStr is %s
", globalStr)
fmt.Printf("globalInt is %d
", globalInt)
fmt.Printf("localStr is %s
", localStr)
fmt.Printf("localInt is %d
", localInt)
}Four variables are demonstrated: global string, global int, local string, and local int. Exported variables must start with an uppercase letter.
Data Structures
var strAry = [10]string{"aa","bb","cc","dd","ee"}
var sliceAry = make([]string,0)
sliceAry = strAry[1:3]
var dic = map[string]int{"apple":1,"watermelon":2}Arrays have fixed length, slices are dynamic views of arrays, and maps store key‑value pairs.
Conditional Statements
localStr := "case3"
if localStr == "case3" {
fmt.Println("into true logic")
} else {
fmt.Println("into false logic")
}
switch localStr {
case "case1": fmt.Println("case1")
case "case2": fmt.Println("case2")
case "case3": fmt.Println("case3")
default: fmt.Println("default")
}Loops
for i := 0; i < 5; i++ {
fmt.Printf("current i %d
", i)
}
for i, str := range sliceAry {
fmt.Printf("slice i %d, str %s
", i, str)
}
for k, v := range dic {
fmt.Printf("key %s, value %d
", k, v)
}Goroutine
go a()
go b()
go c()
time.Sleep(5 * time.Second)Using the go keyword runs functions concurrently, allowing all three to execute in parallel.
Channel
var ch chan int
ch = make(chan int, 1) // buffered channel
ch <- 5
v := <-ch
fmt.Println(v)Channels enable safe communication between goroutines; buffered channels do not block until the buffer is full.
Interface
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct {
height float64
weight float64
}
func (p *Rect) Area() float64 { return p.height * p.weight }
func (p *Rect) Perimeter() float64 { return 2 * (p.height + p.weight) }
func main(){
var s Shape = &Rect{height:10, weight:8}
fmt.Println(s.Area())
fmt.Println(s.Perimeter())
}Any type that implements all methods of an interface satisfies that interface, providing Go’s non‑intrusive polymorphism.
Unit Testing
Test files end with _test.go. Typical test functions are TestMain for setup and TestXxx(t *testing.T) for individual cases. Coverage metrics include function coverage (aim for 100%) and line coverage (typically >60%).
Go Convey
Go Convey adds setup/teardown hooks and expressive assertions such as ShouldEqual, ShouldBeGreaterThan, etc., making test output clearer.
ORM (GORM)
type User struct { Name string; Age int }
args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", username, pwd, addr, database)
db, err := gorm.Open("mysql", args)
if err != nil { panic(err) }
defer db.Close()
user := User{Name:"niuniu", Age:18}
db.Create(&user)
var tmpUser User
db.Where("name = ?", "niuniu").First(&tmpUser)
fmt.Println(tmpUser)GORM simplifies CRUD operations by mapping Go structs to database tables.
Web Server
Standard Library
func SayHello(w http.ResponseWriter, r *http.Request){
w.Write([]byte("hello"))
}
func main(){
http.HandleFunc("/say_hello", SayHello)
http.ListenAndServe(":8080", nil)
}Gin Framework
func SayHello(c *gin.Context){
c.String(http.StatusOK, "hello")
}
func main(){
r := gin.Default()
r.GET("/say_hello", SayHello)
r.Run(":8080")
}Conclusion
This guide provides a rapid introduction to Go, covering installation, basic syntax, package management, concurrency primitives, testing tools, ORM usage, and building simple HTTP services with both the standard library and the Gin framework.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
NiuNiu MaTe
Joined Tencent (nicknamed "Goose Factory") through campus recruitment at a second‑tier university. Career path: Tencent → foreign firm → ByteDance → Tencent. Started as an interviewer at the foreign firm and hopes to help others.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
