Go language study notes.
Learning resources:
Go official learning page
A Tour of Go
Runoob tutorial
Go by example
Outline
Basics
Basic Syntax
- Program structure
1 2 3 4 5
| package main import "fmt" func main() { fmt.Println("Hello, World!") }
|
Variable declaration
var a int = 10, the type comes after the name- Short declaration:
b := "hello", no type annotation needed, used inside functions - Constants:
const pi = 3.14
Data types
- Basic types:
int, float64, bool, string - Derived types: pointers, arrays, structs, slices, maps, channels
Package Management
- Module initialization
go mod init <module-name> - Importing packages
1 2 3 4
| import ( "fmt" "math/rand" )
|
- A name in a package is exported (public) if its first letter is uppercase, and private if it is lowercase
- Packages are Go’s basic unit of organization, similar to libraries or modules in other languages; one package = all the .go files in one directory
Control Flow
Conditionals
1 2 3 4 5
| if x > 0 { } else { }
|
Loops
1 2 3 4 5 6 7 8
| for i := 0; i < 5; i++ { }
for x < 100 { }
|
Switch
1 2 3 4 5 6
| switch day { case "Mon": fmt.Println("周一") default: fmt.Println("其他") }
|
Equivalent to having break added automatically; use fallthrough to continue into the next case.
Data Structures
Arrays and Slices
1 2 3 4 5 6
| arr := [3]int{1, 2, 3}
slice := []int{1, 2} slice = append(slice, 3)
|
Map
1 2 3
| m := make(map[string]int) m["age"] = 25 delete(m, "age")
|
Structs
1 2 3 4 5
| type Person struct { Name string Age int } p := Person{Name: "Tom", Age: 30}
|
Methods and Interfaces
Functions
1 2 3 4 5 6 7 8
| func add(a, b int) int { return a + b }
func swap(x, y string) (string, string) { return y, x }
|
Methods (Receivers)
1 2 3 4 5
| type Circle struct { Radius float64 }
func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius }
|
Interfaces
1 2 3 4 5 6 7
| type Shape interface { Area() float64 }
func printArea(s Shape) { fmt.Println(s.Area()) }
|
Concurrency
Goroutines and Channels
1 2 3 4 5 6 7 8 9
| go func() { fmt.Println("并发执行") }()
ch := make(chan int) go func() { ch <- 1 }() value := <-ch
|
Select
1 2 3 4 5 6
| select { case msg1 := <-ch1: fmt.Println(msg1) case ch2 <- "hi": }
|
Error Handling
1 2 3 4 5
| result, err := someFunction() if err != nil { log.Fatal(err) } defer file.Close()
|
Translated from the Chinese original.