函数
5. 函数 (Functions)
Section titled “5. 函数 (Functions)”// 基本函数func add(a int, b int) int { return a + b}
// 同类型参数可以简写func subtract(a, b int) int { return a - b}函数可以返回多个值,返回类型用括号包裹。
func divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("cannot divide by zero") } return a / b, nil}
result, err := divide(10, 2)if err != nil { // handle error}函数可以接受不定数量的参数。
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total}
sum(1, 2) // 3sum(1, 2, 3, 4) // 106. 指针 (Pointers)
Section titled “6. 指针 (Pointers)”指针存储了变量的内存地址。
x := 10p := &x // p 是一个指向 x 的 int 指针
fmt.Println(*p) // *p 读取 x 的值 (解引用), 输出 10
*p = 20 // 通过指针修改 x 的值fmt.Println(x) // 输出 207. 方法和接口 (Methods & Interfaces)
Section titled “7. 方法和接口 (Methods & Interfaces)”方法 (Method)
Section titled “方法 (Method)”方法是附加到特定类型上的函数。
type Circle struct { Radius float64}
// Area 是一个附加到 Circle 类型上的方法func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius}
c := Circle{Radius: 5}fmt.Println(c.Area())接口 (Interface)
Section titled “接口 (Interface)”接口是一组方法签名的集合。
// Shape 是一个接口type Shape interface { Area() float64}
// Circle 实现了 Shape 接口,因为它有 Area() 方法// Rectangle 也实现了 Shape 接口type Rectangle struct { Width, Height float64}
func (r Rectangle) Area() float64 { return r.Width * r.Height}
// 接受任何实现了 Shape 接口的类型func printArea(s Shape) { fmt.Printf("Area is %f\n", s.Area())}
c := Circle{Radius: 5}r := Rectangle{Width: 3, Height: 4}
printArea(c)printArea(r)8. 错误处理 (Error Handling)
Section titled “8. 错误处理 (Error Handling)”Go 通过显式返回 error 类型的值来处理错误。
import "fmt"
func divide(a, b int) (int, error) { if b == 0 { return 0, fmt.Errorf("division by zero") } return a / b, nil}
func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Result:", result)}9. 并发 (Concurrency)
Section titled “9. 并发 (Concurrency)”Goroutine
Section titled “Goroutine”Goroutine 是由 Go 运行时管理的轻量级线程。
import ( "fmt" "time")
func say(s string) { for i := 0; i < 3; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) }}
func main() { go say("world") // 启动一个新的 goroutine say("hello") // 当前 goroutine}// 输出可能是交错的 "hello" 和 "world"Channel
Section titled “Channel”Channel 是用于在 Goroutine 之间通信的管道。
// 创建一个 string 类型的 channelch := make(chan string)
go func() { ch <- "ping" // 发送数据到 channel}()
msg := <-ch // 从 channel 接收数据fmt.Println(msg) // "ping"10. 常用标准库 (Standard Library)
Section titled “10. 常用标准库 (Standard Library)”提供了格式化 I/O 的功能。
fmt.Println(...): 打印并换行fmt.Printf(format, ...): 格式化打印fmt.Sprintf(format, ...): 格式化为字符串fmt.Errorf(format, ...): 创建一个 error
name := "Go"age := 10fmt.Printf("Name: %s, Age: %d\n", name, age)// Verb:// %v: 默认格式的值// %+v: 打印结构体时会添加字段名// %#v: Go 语法表示的值// %T: 值的类型strings
Section titled “strings”提供了字符串操作函数。
strings.Contains(s, substr): 是否包含子串strings.Split(s, sep): 分割字符串strings.Join(a []string, sep string): 连接字符串strings.HasPrefix(s, prefix): 是否有指定前缀strings.HasSuffix(s, suffix): 是否有指定后缀strings.ToLower(s)/strings.ToUpper(s): 大小写转换strings.TrimSpace(s): 去除首尾空白
strconv
Section titled “strconv”提供了字符串与其他基本数据类型之间的转换。
strconv.Itoa(i int): int 转 stringstrconv.Atoi(s string): string 转 intstrconv.ParseFloat(s string, bitSize int): string 转 floatstrconv.FormatFloat(f float64, ...): float 转 string