### 环境安装 ```text https://go.dev/dl/ https://golang.google.cn/dl/ ``` ### Hello, World! ```go package main import "fmt" func main() { fmt.Println("Hello, World!") } ``` ### 基础 #### 变量和数据类型 ```go package main import "fmt" func main() { // 字符串 name := "张三" // 整数 age := 25 // 浮点数 height := 1.75 // 布尔值 isStudent := true // 数组 hobbies := [3]string{"读书", "编程", "音乐"} // 切片(动态数组) scores := []int{85, 92, 78} fmt.Printf("姓名: %s\n", name) fmt.Printf("年龄: %d 岁\n", age) fmt.Printf("身高: %.2f 米\n", height) fmt.Printf("是学生: %t\n", isStudent) fmt.Printf("爱好: %v\n", hobbies) fmt.Printf("成绩: %v\n", scores) } ``` #### 条件判断 ```go package main import "fmt" func getGrade(score int) string { if score >= 90 { return "优秀" } else if score >= 80 { return "良好" } else if score >= 60 { return "及格" } else { return "不及格" } } func main() { fmt.Println(getGrade(95)) // 输出: 优秀 fmt.Println(getGrade(75)) // 输出: 及格 // switch 语句 grade := "B" switch grade { case "A": fmt.Println("优秀") case "B": fmt.Println("良好") case "C": fmt.Println("及格") default: fmt.Println("不及格") } } ``` #### 循环 ```go package main import "fmt" func main() { // for循环 - 遍历切片 fruits := []string{"苹果", "香蕉", "橙子", "葡萄"} fmt.Println("我喜欢的水果:") for i, fruit := range fruits { fmt.Printf("%d. %s\n", i+1, fruit) } // 传统的for循环 fmt.Println("\n计数到5:") for i := 1; i <= 5; i++ { fmt.Println(i) } // while循环(用for实现) count := 1 fmt.Println("\n用while风格计数:") for count <= 3 { fmt.Println(count) count++ } } ``` #### 切片和Map ```go package main import "fmt" func main() { // 切片操作 numbers := []int{1, 2, 3, 4, 5} // 添加元素 numbers = append(numbers, 6, 7) fmt.Println("添加后:", numbers) // 切片切片 slice1 := numbers[1:4] // [2,3,4] fmt.Println("切片:", slice1) // Map(字典) studentScores := map[string]int{ "张三": 85, "李四": 92, "王五": 78, } // 添加元素 studentScores["赵六"] = 88 // 遍历map for name, score := range studentScores { fmt.Printf("%s: %d分\n", name, score) } // 检查key是否存在 if score, exists := studentScores["张三"]; exists { fmt.Printf("张三的分数是: %d\n", score) } } ``` #### 错误处理 ```go package main import ( "errors" "fmt" ) // 自定义错误 func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("除数不能为零") } return a / b, nil } func main() { // 正常情况 result, err := divide(10, 2) if err != nil { fmt.Println("错误:", err) } else { fmt.Printf("结果: %.2f\n", result) } // 错误情况 result, err = divide(10, 0) if err != nil { fmt.Println("错误:", err) } else { fmt.Printf("结果: %.2f\n", result) } // defer 延迟执行(类似finally) defer fmt.Println("程序执行完成") fmt.Println("正在计算...") } ``` ### 函数 #### 1.普通函数 (Function) ```go // 普通函数 func 函数名(参数) 返回值 { // 函数体 } ``` #### 2.方法 (Method) ```go // 方法 = 函数 + 接收者 func (接收者) 方法名(参数) 返回值 { // 方法体 } ``` #### 3.接口方法 (Interface Method) ```go // 接口方法(在接口中定义) type 接口名 interface { 方法名(参数) 返回值 // 只有方法签名,没有实现 } ``` #### 4.自定义函数类型 (Custom Function Type) ```go // 自定义函数类型 type 类型名 func(参数) 返回值 // 为自定义函数类型添加方法 func (f 类型名) 方法名(参数) 返回值 { // 方法体 } ``` #### 5.泛型函数 (Generic Function) ```go // 泛型函数 func 函数名[T 约束](参数 T) T { // 函数体 } // 泛型方法 func (接收者) 方法名[T 约束](参数 T) T { // 方法体 } // 泛型接口 type 接口名[T 约束] interface { 方法名(参数 T) T } ``` #### 6.泛型自定义函数类型 ```go // 泛型自定义函数类型 type 类型名[T 约束] func(参数 T) T // 为泛型自定义函数类型添加泛型方法 func (f 类型名[T]) 方法名[U 约束](参数 U) U { // 方法体 } ``` #### 层次关系 ```text 普通函数 → 基础构建块 ↓ 方法 → 普通函数 + 接收者(绑定到类型) ↓ 接口方法 → 方法的抽象契约(只有签名) ↓ 自定义函数类型 → 函数作为一等公民的类型化 ↓ 泛型函数/方法 → 类型参数化的通用实现 ↓ 泛型接口 → 支持类型参数的抽象契约 ``` ### 作用域 #### 块作用域 ```go package main import "fmt" func main() { // 作用域起点:变量 x 在整个 main 函数块内可见 x := 10 fmt.Println(x) // 输出 10 { // 这是一个内部块 y := 20 // 变量 y 只在这个内部块中可见 fmt.Println(x, y) // 输出 10 20 (x 可见,y 可见) } // fmt.Println(y) // 编译错误!undefined: y (y 的作用域结束了) if x > 5 { // if 语句隐式块开始 z := 30 // z 的作用域仅限于这个 if 块 fmt.Println(x, z) // 输出 10 30 } // fmt.Println(z) // 编译错误!undefined: z (z 的作用域结束了) for i := 0; i < 3; i++ { // i 的作用域是整个 for 语句块(包括条件判断和循环体) fmt.Println(i) } // fmt.Println(i) // 编译错误!undefined: i (i 的作用域结束了) } ``` #### 词法作用域 ```go package main import "fmt" func outer() func() int { count := 0 // count 的作用域是 outer 函数 // 内部函数 inner 是一个闭包,它“捕获”了变量 count inner := func() int { count++ // inner 可以访问其外部作用域(即 outer 函数)的变量 count return count } return inner // 返回这个闭包函数 } func main() { counter := outer() fmt.Println(counter()) // 输出 1 fmt.Println(counter()) // 输出 2 (count 的状态被保留了) anotherCounter := outer() // 创建一个新的闭包,拥有自己独立的 count 变量 fmt.Println(anotherCounter()) // 输出 1 } ``` #### 包作用域 ```go package main import "fmt" // 包级作用域(包内所有文件可见) var globalVar = "I am global" // 小写开头,仅包内可见 const GlobalConst = "I am public" // 大写开头,导出,其他包可访问 func main() { fmt.Println(globalVar) // 可见 fmt.Println(GlobalConst) // 可见 someFunction() // 可见 } ``` ```go package main import "fmt" // 这个函数在整个包内都可见 func someFunction() { fmt.Println("Accessing from another file:", globalVar) // globalVar 在此文件可见 } // 这个函数是私有的,仅在包内可用 func privateFunc() { // ... } ``` ```go package otherpackage import "mypackage" func someFunc() { // fmt.Println(mypackage.globalVar) // 错误!globalVar 是小写,不可见 fmt.Println(mypackage.GlobalConst) // 正确!GlobalConst 是大写,已导出 // mypackage.privateFunc() // 错误!privateFunc 是小写,不可见 } ``` ### 结构体和方法 ```go package main import "fmt" // 定义结构体 type Student struct { Name string ID string Grades []int } // 为结构体定义方法 func (s *Student) AddGrade(grade int) { s.Grades = append(s.Grades, grade) } func (s Student) GetAverage() float64 { if len(s.Grades) == 0 { return 0 } sum := 0 for _, grade := range s.Grades { sum += grade } return float64(sum) / float64(len(s.Grades)) } func (s Student) DisplayInfo() { fmt.Printf("学生姓名: %s\n", s.Name) fmt.Printf("学号: %s\n", s.ID) fmt.Printf("成绩: %v\n", s.Grades) fmt.Printf("平均分: %.2f\n", s.GetAverage()) } func main() { // 创建结构体实例 student1 := Student{ Name: "小明", ID: "2024001", } student1.AddGrade(85) student1.AddGrade(92) student1.AddGrade(78) student1.DisplayInfo() } ```