[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-14":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":16,"prev_article":17,"next_article":21,"created_at":25},14,"Go 语言基础入门","Go language basics introduction","Go 语言基础入门：从语法到核心概念 Go 语言（又称 Golang）是由 Google 开发的一门静态类型、编译型编程语言，自 2009 年正式发布以来，凭借其简洁的语法、高效的性能和强大的并发支持，在云原生、后端开发等领域迅速崛起","Getting Started with Go Language Basics: From Syntax to Core Concepts Go Language (also known as Golang) is a statically typed, compiled programming language developed by Google, which has risen rapidly in cloud-native, back-end development, and other fields since its official release in 2009 with its concise syntax, efficient performance, and strong concurrency support","![go](https:\u002F\u002Fpic2.zhimg.com\u002Fv2-55a9aba97d1e214f849ab2e55f3dabff_1440w.jpg?source=172ae18b)\n\n\n# Go 语言基础入门：从语法到核心概念\n\nGo 语言（又称 Golang）是由 Google 开发的一门静态类型、编译型编程语言，自 2009 年正式发布以来，凭借其简洁的语法、高效的性能和强大的并发支持，在云原生、后端开发等领域迅速崛起。本文将系统介绍 Go 语言的基础知识，帮助初学者快速掌握这门语言的核心语法和编程思想。\n\n## 一、Go 语言的特点与优势\n\nGo 语言在设计之初就融合了多种编程语言的优点，同时规避了传统语言的复杂特性，其核心特点包括：\n\n\n\n*   **简洁易学**：语法精炼，去除了冗余的语法元素（如没有类继承、泛型早期不支持等），降低学习成本\n\n*   **静态类型**：编译时类型检查，减少运行时错误，提高代码健壮性\n\n*   **编译快速**：编译速度远超 C++ 和 Java，支持跨平台编译（一次编译，到处运行）\n\n*   **原生并发**：通过 goroutine 和 channel 实现轻量级并发，简化并发编程复杂度\n\n*   **内存安全**：内置垃圾回收机制，无需手动管理内存\n\n*   **丰富标准库**：网络、IO、加密等基础功能开箱即用，避免重复造轮子\n\n## 二、环境搭建与第一个程序\n\n### 安装 Go 环境\n\n\n\n1.  访问[Go 官](https:\u002F\u002Fgolang.org\u002Fdl\u002F)[方下载](https:\u002F\u002Fgolang.org\u002Fdl\u002F)[页](https:\u002F\u002Fgolang.org\u002Fdl\u002F)，根据操作系统选择对应安装包\n\n2.  安装完成后，打开终端执行`go version`验证安装成功：\n\n\n\n```\ngo version go1.21.0 darwin\u002Famd64  # 输出示例\n```\n\n### 编写 fuck World\n\n创建`hello.go`文件，输入以下代码：\n\n\n\n``` Go\npackage main  \u002F\u002F 声明主包（可执行程序必须在main包中）\n\nimport \"fmt\"  \u002F\u002F 导入标准库的fmt包（用于输入输出）\n\nfunc main() {  \u002F\u002F 程序入口函数（必须为main）\n\n    fmt.Println(\"fuck, world!\")  \u002F\u002F 打印字符串并换行\n\n}\n```\n\n运行程序：\n\n\n\n``` shell\ngo run hello.go  # 直接运行\n\n\\# 或先编译再运行\n\ngo build hello.go\n\n.\u002Fhello  # Linux\u002FMac\n\nhello.exe  # Windows\n```\n\n输出结果：\n\n\n\n```\nHello, Go!\n```\n\n## 三、基本语法要素\n\n### 变量与常量\n\nGo 语言声明变量有多种方式，最常用的是`var`关键字和短变量声明符`:=`：\n\n\n\n``` Go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\n    \u002F\u002F 1. 完整声明（指定类型）\n\n    var age int = 25\n\n    \u002F\u002F 2. 类型推断（省略类型，由赋值推断）\n\n    var name = \"GoLang\"\n\n    \u002F\u002F 3. 短变量声明（函数内可用，自动推断类型）\n\n    score := 95.5\n\n    \n\n    fmt.Printf(\"年龄：%d，名称：%s，分数：%.1f\\n\", age, name, score)\n\n    \n\n    \u002F\u002F 常量声明（使用const关键字，值不可修改）\n\n    const pi = 3.14159\n\n    fmt.Println(\"圆周率：\", pi)\n\n}\n```\n\n**注意**：短变量声明`:=`只能在函数内部使用，且至少要声明一个新变量。\n\n### 数据类型\n\nGo 语言提供丰富的数据类型，可分为基本类型和复合类型：\n\n\n\n1.  **基本类型**：\n\n*   整数：`int`（随系统位数变化）、`int8`\u002F`int16`\u002F`int32`\u002F`int64`（固定长度）\n\n*   浮点数：`float32`（单精度）、`float64`（双精度，默认）\n\n*   布尔值：`bool`（`true`\u002F`false`）\n\n*   字符串：`string`（不可变序列）\n\n1.  **复合类型**：\n\n*   数组：`[n]T`（固定长度的同类型元素集合）\n\n*   切片：`[]T`（动态长度的序列，更常用）\n\n*   映射：`map[K]V`（键值对集合）\n\n*   结构体：`struct`（自定义复合类型）\n\n示例：\n\n\n\n``` Go\n\u002F\u002F 数组（长度固定）\n\nvar nums \\[3]int = \\[3]int{1, 2, 3}\n\n\u002F\u002F 切片（动态长度）\n\nscores := \\[]float64{90.5, 88.0, 95.5}\n\n\u002F\u002F 映射（键值对）\n\nuser := map\\[string]string{\n\n    \"name\": \"张三\",\n\n    \"city\": \"北京\",\n\n}\n```\n\n### 控制流语句\n\n#### 条件语句（if-else）\n\n\n\n``` Go\nfunc main() {\n\n    score := 85\n\n    \u002F\u002F if后无括号，条件体必须换行且缩进\n\n    if score &gt;= 90 {\n\n        fmt.Println(\"优秀\")\n\n    } else if score &gt;= 60 {\n\n        fmt.Println(\"及格\")\n\n    } else {\n\n        fmt.Println(\"不及格\")\n\n    }\n\n    \n\n    \u002F\u002F 特殊用法：条件前可加初始化语句\n\n    if age := 18; age &gt;= 18 {\n\n        fmt.Println(\"成年\")\n\n    }\n\n}\n```\n\n#### 循环语句（for）\n\nGo 语言只有`for`一种循环结构，但可实现多种循环方式：\n\n\n\n``` Go\nfunc main() {\n\n    \u002F\u002F 1. 基本for循环（类似C语言）\n\n    for i := 0; i &lt; 5; i++ {\n\n        fmt.Print(i, \" \")\n\n    }\n\n    fmt.Println()\n\n    \n\n    \u002F\u002F 2. 类似while循环\n\n    count := 0\n\n    for count &lt; 3 {\n\n        fmt.Println(\"循环次数：\", count)\n\n        count++\n\n    }\n\n    \n\n    \u002F\u002F 3. 无限循环（需配合break退出）\n\n    sum := 0\n\n    for {\n\n        sum += 10\n\n        if sum &gt;= 50 {\n\n            break  \u002F\u002F 退出循环\n\n        }\n\n    }\n\n    fmt.Println(\"总和：\", sum)\n\n}\n``` Go\n\n#### 分支语句（switch）\n\nGo 的 switch 相比其他语言更灵活，支持任意类型比较：\n\n\n\n``` Go\nfunc main() {\n\n    day := 3\n\n    \u002F\u002F 自动break，无需显式添加\n\n    switch day {\n\n    case 1:\n\n        fmt.Println(\"星期一\")\n\n    case 2:\n\n        fmt.Println(\"星期二\")\n\n    case 3:\n\n        fmt.Println(\"星期三\")\n\n    default:\n\n        fmt.Println(\"其他星期\")\n\n    }\n\n    \n\n    \u002F\u002F 多条件匹配\n\n    score := 88\n\n    switch {\n\n    case score &gt;= 90:\n\n        fmt.Println(\"A\")\n\n    case score &gt;= 80:\n\n        fmt.Println(\"B\")\n\n    default:\n\n        fmt.Println(\"C\")\n\n    }\n\n}\n```\n\n## 四、函数与包\n\n### 函数定义与调用\n\n函数是 Go 语言的基本执行单元，定义格式如下：\n\n\n\n``` Go\n\u002F\u002F 函数声明：func 函数名(参数列表) 返回值类型 { 函数体 }\n\nfunc add(a int, b int) int {\n\n    return a + b\n\n}\n\n\u002F\u002F 简化参数类型（同类型参数可合并）\n\nfunc multiply(x, y float64) float64 {\n\n    return x \\* y\n\n}\n\n\u002F\u002F 多返回值（Go语言特色）\n\nfunc divide(dividend, divisor float64) (float64, error) {\n\n    if divisor == 0 {\n\n        return 0, fmt.Errorf(\"除数不能为0\")\n\n    }\n\n    return dividend \u002F divisor, nil\n\n}\n\nfunc main() {\n\n    sum := add(3, 5)\n\n    fmt.Println(\"和：\", sum)\n\n    \n\n    product := multiply(2.5, 4)\n\n    fmt.Println(\"积：\", product)\n\n    \n\n    result, err := divide(10, 2)\n\n    if err != nil {\n\n        fmt.Println(\"错误：\", err)\n\n    } else {\n\n        fmt.Println(\"商：\", result)\n\n    }\n\n}\n```\n\n### 包管理\n\nGo 语言通过包（package）组织代码，每个 Go 文件都属于一个包：\n\n\n\n*   **包声明**：文件首行的`package 包名`指定所属包\n\n*   **导入包**：使用`import`语句导入其他包，如`import \"fmt\"`\n\n*   **可见性**：变量 \u002F 函数名首字母大写表示公开（可被其他包访问），小写表示私有\n\n示例项目结构：\n\n\n\n```\nmyproject\u002F\n\n├── main.go         # 主包（package main）\n\n└── mathutil\u002F\n\n    └── calculator.go  # 工具包（package mathutil）\n```\n\n`calculator.go`内容：\n\n\n\n``` Go\npackage mathutil\n\n\u002F\u002F 公开函数（首字母大写）\n\nfunc Add(a, b int) int {\n\n    return a + b\n\n}\n\n\u002F\u002F 私有函数（首字母小写，仅包内可见）\n\nfunc subtract(x, y int) int {\n\n    return x - y\n\n}\n```\n\n`main.go`调用：\n\n\n\n```\npackage main\n\nimport (\n\n    \"fmt\"\n\n    \"myproject\u002Fmathutil\"  \u002F\u002F 导入自定义包\n\n)\n\nfunc main() {\n\n    total := mathutil.Add(10, 20)\n\n    fmt.Println(\"总和：\", total)\n\n}\n```\n\n## 五、结构体与接口\n\n### 结构体（struct）\n\n结构体用于定义自定义复合类型，组合多个不同类型的字段：\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\n\u002F\u002F 定义结构体\n\ntype Person struct {\n\n    Name string  \u002F\u002F 公开字段\n\n    Age  int     \u002F\u002F 公开字段\n\n    addr string  \u002F\u002F 私有字段（仅包内访问）\n\n}\n\n\u002F\u002F 结构体方法（绑定到结构体的函数）\n\nfunc (p Person) Introduce() string {\n\n    return fmt.Sprintf(\"我叫%s，今年%d岁\", p.Name, p.Age)\n\n}\n\n\u002F\u002F 指针接收者（可修改结构体内容）\n\nfunc (p \\*Person) Grow() {\n\n    p.Age++\n\n}\n\nfunc main() {\n\n    \u002F\u002F 创建结构体实例\n\n    person := Person{\n\n        Name: \"张三\",\n\n        Age:  28,\n\n    }\n\n    \n\n    fmt.Println(person.Introduce())  \u002F\u002F 调用方法\n\n    person.Grow()                    \u002F\u002F 年龄增长\n\n    fmt.Println(\"一年后：\", person.Introduce())\n\n}\n```\n\n### 接口（interface）\n\n接口定义了一组方法签名，无需实现细节，实现了这些方法的类型即 \"隐式\" 实现了接口：\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\n\u002F\u002F 定义接口（方法集合）\n\ntype Speaker interface {\n\n    Speak() string\n\n}\n\n\u002F\u002F 实现接口的类型1\n\ntype Dog struct{}\n\nfunc (d Dog) Speak() string {\n\n    return \"汪汪汪\"\n\n}\n\n\u002F\u002F 实现接口的类型2\n\ntype Cat struct{}\n\nfunc (c Cat) Speak() string {\n\n    return \"喵喵喵\"\n\n}\n\n\u002F\u002F 接收接口类型参数\n\nfunc makeSound(s Speaker) {\n\n    fmt.Println(s.Speak())\n\n}\n\nfunc main() {\n\n    var animal Speaker\n\n    animal = Dog{}\n\n    makeSound(animal)  \u002F\u002F 输出：汪汪汪\n\n    \n\n    animal = Cat{}\n\n    makeSound(animal)  \u002F\u002F 输出：喵喵喵\n\n}\n```\n\n接口是 Go 语言实现多态的核心机制，极大提高了代码的灵活性和可扩展性。\n\n## 六、并发编程基础\n\nGo 语言的并发模型是其最大特色之一，通过 goroutine 和 channel 实现轻量级并发：\n\n### Goroutine（协程）\n\nGoroutine 是 Go 语言特有的轻量级线程，由 Go 运行时管理，创建成本极低：\n\n\n\n```\npackage main\n\nimport (\n\n    \"fmt\"\n\n    \"time\"\n\n)\n\n\u002F\u002F 并发执行的函数\n\nfunc printNumbers() {\n\n    for i := 0; i &lt; 5; i++ {\n\n        time.Sleep(100 \\* time.Millisecond)  \u002F\u002F 模拟耗时操作\n\n        fmt.Printf(\"%d \", i)\n\n    }\n\n}\n\nfunc printLetters() {\n\n    for c := 'a'; c &lt; 'f'; c++ {\n\n        time.Sleep(150 \\* time.Millisecond)\n\n        fmt.Printf(\"%c \", c)\n\n    }\n\n}\n\nfunc main() {\n\n    \u002F\u002F 启动两个goroutine（前面加go关键字）\n\n    go printNumbers()\n\n    go printLetters()\n\n    \n\n    \u002F\u002F 主goroutine等待子goroutine完成（实际开发用sync.WaitGroup）\n\n    time.Sleep(2 \\* time.Second)\n\n    fmt.Println(\"\\n程序结束\")\n\n}\n```\n\n运行结果（顺序可能不同，体现并发特性）：\n\n\n\n```\n0 a 1 b 2 c 3 d 4 e \n\n程序结束\n```\n\n### Channel（通道）\n\nChannel 用于 goroutine 之间的通信，实现数据同步：\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\n\u002F\u002F 向通道发送数据\n\nfunc sendData(ch chan&lt;- int) {\n\n    for i := 1; i &lt;= 5; i++ {\n\n        ch &lt;- i  \u002F\u002F 发送数据到通道\n\n    }\n\n    close(ch)  \u002F\u002F 关闭通道\n\n}\n\n\u002F\u002F 从通道接收数据\n\nfunc receiveData(ch &lt;-chan int, done chan&lt;- bool) {\n\n    for num := range ch {  \u002F\u002F 循环接收直到通道关闭\n\n        fmt.Println(\"收到数据：\", num)\n\n    }\n\n    done &lt;- true  \u002F\u002F 通知完成\n\n}\n\nfunc main() {\n\n    \u002F\u002F 创建通道（指定元素类型）\n\n    dataChan := make(chan int)\n\n    doneChan := make(chan bool)\n\n    \n\n    \u002F\u002F 启动goroutine\n\n    go sendData(dataChan)\n\n    go receiveData(dataChan, doneChan)\n\n    \n\n    \u002F\u002F 等待接收完成\n\n    &lt;-doneChan\n\n    fmt.Println(\"所有数据处理完毕\")\n\n}\n```\n\n## 七、错误处理\n\nGo 语言没有异常机制，通过返回值显式处理错误：\n\n\n\n```\npackage main\n\nimport (\n\n    \"errors\"\n\n    \"fmt\"\n\n)\n\n\u002F\u002F 返回错误的函数\n\nfunc divide(a, b float64) (float64, error) {\n\n    if b == 0 {\n\n        \u002F\u002F 返回自定义错误\n\n        return 0, errors.New(\"除数不能为零\")\n\n    }\n\n    return a \u002F b, nil  \u002F\u002F 成功时错误为nil\n\n}\n\nfunc main() {\n\n    result, err := divide(10, 2)\n\n    if err != nil {  \u002F\u002F 检查错误\n\n        fmt.Println(\"发生错误：\", err)\n\n    } else {\n\n        fmt.Println(\"结果：\", result)\n\n    }\n\n    \n\n    \u002F\u002F 错误示例\n\n    result, err = divide(5, 0)\n\n    if err != nil {\n\n        fmt.Println(\"发生错误：\", err)\n\n    }\n\n}\n```\n\n## 八、总结与进阶方向\n\n本文介绍了 Go 语言的基础语法，包括变量声明、数据类型、控制流、函数、结构体、接口、并发等核心概念。要真正掌握 Go 语言，还需要深入学习以下内容：\n\n\n\n*   标准库详解（`net\u002Fhttp`、`encoding\u002Fjson`等常用包）\n\n*   并发模式（`sync`包、goroutine 池、select 语句）\n\n*   内存管理与性能优化\n\n*   测试与性能分析（`go test`、`pprof`）\n\n*   实际项目开发（Web 服务、工具开发等）\n\nGo 语言以其简洁高效的特性，特别适合构建高性能的后端服务和云原生应用。通过不断实践，你会逐渐体会到这门语言的独特魅力。\n\n想要进一步学习，可以访问[Go 官方文档](https:\u002F\u002Fgolang.org\u002Fdoc\u002F)或阅读《The Go Programming Language》等经典书籍。\n","! [go] (https:\u002F\u002Fpic2.zhimg.com\u002Fv2-55a9aba97d1e214f849ab2e55f3dabff_1440w.jpg?source=172ae18b)\n\n\n# Go Language Basics Introduction: From Grammar to Core Concepts\n\nGo Language (also known as Golang) is a statically typed, compiled programming language developed by Google, which has risen rapidly in cloud-native, back-end development, and other fields since its official release in 2009 with its concise syntax, efficient performance, and strong concurrency support. This article will systematically introduce the basics of the Go language and help beginners quickly grasp the core syntax and programming ideas of this language.\n\n## 1. Characteristics and advantages of Go language\n\nThe Go language is designed to incorporate the advantages of multiple programming languages while avoiding the complex features of traditional languages, and its core features include:\n\n\n\n* **Concise and easy to learn**: The grammar is refined, removing redundant grammatical elements (such as no class inheritance, generic early support, etc.), reducing learning costs\n\n* **Static Type**: Compile-time type checking to reduce runtime errors and improve code robustness\n\n* **Fast Compilation**: Compile faster than C++ and Java, supporting cross-platform compilation (compile once, run anywhere)\n\n**Native Concurrency**: Implements lightweight concurrency with goroutines and channels, simplifying concurrent programming complexity\n\n* **Memory Security**: Built-in garbage collection mechanism, eliminating the need to manually manage memory\n\n* **Rich Standard Library**: Basic functions such as networking, IO, and encryption are used out of the box, avoiding reinventing wheels\n\n## 2. Environment construction and the first program\n\n### Install the Go environment\n\n\n\n1. Go to [Go Official](https:\u002F\u002Fgolang.org\u002Fdl\u002F)[Party Download](https:\u002F\u002Fgolang.org\u002Fdl\u002F)[Page](https:\u002F\u002Fgolang.org\u002Fdl\u002F) and select the corresponding installation package according to the operating system\n\n2. After the installation is complete, open the terminal and perform 'go version' to verify that the installation is successful:\n\n\n\n```\nGo version go1.21.0 darwin\u002Famd64 # output example\n```\n\n### Writing fuck World\n\nCreate a 'hello.go' file and enter the following code:\n\n\n\n``` Go\npackage main \u002F\u002F declare the main package (the executable must be in the main package)\n\nimport \"fmt\" \u002F\u002F Import the FMT package of the standard library (for input and output)\n\nfunc main() { \u002F\u002F program entry function (must be main)\n\n    fmt. Println(\"fuck, world!\")  Print the string and wrap the line\n\n}\n```\n\nRunning Program:\n\n\n\n``` shell\ngo run hello.go # run directly\n\n\\# or compile and then run\n\ngo build hello.go\n\n.\u002Fhello  # Linux\u002FMac\n\nhello.exe  # Windows\n```\n\nOutput:\n\n\n\n```\nHello, Go!\n```\n\n## 3. Basic grammar elements\n\n### Variables vs. Constants\n\nThere are many ways to declare variables in the Go language, the most commonly used are the 'var' keyword and the short variable declarer ':=':\n\n\n\n``` Go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\n    \u002F\u002F 1. Full declaration (specify type)\n\n    var age int = 25\n\n    \u002F\u002F 2. Type inference (omitting types, inferred by assignments)\n\n    var name = \"GoLang\"\n\n    \u002F\u002F 3. Short variable declaration (available within functions, auto-inferred type)\n\n    score := 95.5\n\n    \n\n    fmt. Printf(\"age:%d,name:%s,score:%.1f\\n\", age, name, score)\n\n    \n\n    Constant declaration (use the const keyword, the value cannot be modified)\n\n    const pi = 3.14159\n\n    fmt. Println(\"pi:\", pi)\n\n}\n```\n\nNote: Short variables declare ':=' only within a function and at least one new variable must be declared.\n\n### Data Types\n\nGo provides a wealth of data types, which can be divided into basic and compound types:\n\n\n\n1. **Basic Types**:\n\n* Integer: 'int' (varies with the number of digits in the system), 'int8'\u002F'int16'\u002F'int32'\u002F'int64' (fixed length)\n\n* Floating-point numbers: 'float32' (single precision), 'float64' (double precision, default)\n\n* Boolean: 'bool'('true'\u002F'false')\n\n* String: 'string' (immutable sequence)\n\n1. **Composite Type**:\n\n* Array: '[n]T' (fixed length collection of elements of the same type)\n\n* Slice: '[]T' (dynamically length sequence, more commonly used)\n\n* Mapping: 'map[K]V' (key-value pair set)\n\n* Struct: 'struct' (custom compound type)\n\nExample:\n\n\n\n``` Go\nArray (fixed length)\n\nvar nums \\[3]int = \\[3]int{1, 2, 3}\n\nSlice (dynamic length)\n\nscores := \\[]float64{90.5, 88.0, 95.5}\n\nMapping (key-value pairs)\n\nuser := map\\[string]string{\n\n    \"name\": \"Zhang San\",\n\n    \"city\": \"Beijing\",\n\n}\n```\n\n### Control flow statements\n\n#### Conditional Statements (if-else)\n\n\n\n``` Go\nfunc main() {\n\n    score := 85\n\n    If is followed by no parentheses, the conditional body must wrap and indent\n\n    if score >= 90 {\n\n        fmt. Println (\"Excellent\")\n\n    } else if score >= 60 {\n\n        fmt. Println(\"pass\")\n\n    } else {\n\n        fmt. Println (\"fail\")\n\n    }\n\n    \n\n    Special usage: You can add an initialization statement before the condition\n\n    if age := 18; age >= 18 {\n\n        fmt. Println (\"Adult\")\n\n    }\n\n}\n```\n\n#### Circular Statement (for)\n\nThe Go language only has a loop structure called 'for', but it can implement a variety of loop methods:\n\n\n\n``` Go\nfunc main() {\n\n    \u002F\u002F 1. Basic for loop (similar to C)\n\n    for i := 0; i \u003C 5; i++ {\n\n        fmt. Print(i, \" \")\n\n    }\n\n    fmt. Println()\n\n    \n\n    \u002F\u002F 2. Similar to a while loop\n\n    count := 0\n\n    for count \u003C 3 {\n\n        fmt. Println(\"Cycles:\", count)\n\n        count++\n\n    }\n\n    \n\n    \u002F\u002F 3. Infinite loop (requires break to exit)\n\n    sum := 0\n\n    for {\n\n        sum += 10\n\n        if sum >= 50 {\n\n            break \u002F\u002F Exit the loop\n\n        }\n\n    }\n\n    fmt. Println(\"sum:\", sum)\n\n}\n``` Go\n\n#### Branch Statement (Switch)\n\nGo's switch is more flexible than other languages and supports arbitrary comparisons:\n\n\n\n``` Go\nfunc main() {\n\n    day := 3\n\n    Auto-break, no need to add explicitly\n\n    switch day {\n\n    case 1:\n\n        fmt. Println (\"Monday\")\n\n    case 2:\n\n        fmt. Println (\"Tuesday\")\n\n    case 3:\n\n        fmt. Println (\"Wednesday\")\n\n    default:\n\n        fmt. Println (\"Other Weeks\")\n\n    }\n\n    \n\n    Multi-condition matching\n\n    score := 88\n\n    switch {\n\n    case score >= 90:\n\n        fmt. Println(\"A\")\n\n    case score >= 80:\n\n        fmt. Println(\"B\")\n\n    default:\n\n        fmt. Println(\"C\")\n\n    }\n\n}\n```\n\n## 4. Functions and packages\n\n### Function definition and calling\n\nFunctions are the basic units of execution of the Go language, defined in the following format:\n\n\n\n``` Go\nFunction declaration: func function name (parameter list) return value type { function body }\n\nfunc add(a int, b int) int {\n\n    return a + b\n\n}\n\nSimplified parameter types (the same type of parameters can be merged)\n\nfunc multiply(x, y float64) float64 {\n\n    return x \\* y\n\n}\n\nMultiple return values (Go language feature)\n\nfunc divide(dividend, divisor float64) (float64, error) {\n\n    if divisor == 0 {\n\n        return 0, fmt. Errorf(\"Divisor cannot be 0\")\n\n    }\n\n    return dividend \u002F divisor, nil\n\n}\n\nfunc main() {\n\n    sum := add(3, 5)\n\n    fmt. Println(\"and:\", sum)\n\n    \n\n    product := multiply(2.5, 4)\n\n    fmt. Println(\"product:\", product)\n\n    \n\n    result, err := divide(10, 2)\n\n    if err != nil {\n\n        fmt. Println(\"Error:\", err)\n\n    } else {\n\n        fmt. Println(\"Quotient:\", result)\n\n    }\n\n}\n```\n\n### Package management\n\nThe Go language organizes code through packages, and each Go file belongs to a package:\n\n\n\n* **Package Statement**: The 'package name' in the first line of the document specifies the package to which it belongs\n\n**Import package**: Import other packages using the 'import' statement, such as 'import \"fmt\"'\n\n* **Visibility**: The first letter of the variable \u002F function name is uppercase for public (accessible by other packages), and lowercase for private\n\nExample project structure:\n\n\n\n```\nmyproject\u002F\n\n├── main.go # Package Main\n\n└── mathutil\u002F\n\n    └── calculator.go # Package Mathutil\n```\n\n'calculator.go' content:\n\n\n\n``` Go\npackage mathutil\n\nPublic functions (capitalization)\n\nfunc Add(a, b int) int {\n\n    return a + b\n\n}\n\nPrivate function (lowercase, visible only in the package)\n\nfunc subtract(x, y int) int {\n\n    return x - y\n\n}\n```\n\n'main.go' call:\n\n\n\n```\npackage main\n\nimport (\n\n    \"fmt\"\n\n    \"myproject\u002Fmathutil\" \u002F\u002F Import custom packages\n\n)\n\nfunc main() {\n\n    total := mathutil. Add(10, 20)\n\n    fmt. Println(\"Sum:\", total)\n\n}\n```\n\n## 5. Structs and interfaces\n\n### Struct\n\nThe struct is used to define custom compound types, combining fields of different types:\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\nDefine structs\n\ntype Person struct {\n\n    Name string \u002F\u002F public field\n\n    Age int \u002F\u002F public field\n\n    addr string \u002F\u002F private field (in-package access only)\n\n}\n\nStruct methods (functions bound to structs)\n\nfunc (p Person) Introduce() string {\n\n    return fmt. Sprintf (\"My name is %s, and I'm %d this year\", p.Name, p.Age)\n\n}\n\nPointer Receiver (modify struct content)\n\nfunc (p \\*Person) Grow() {\n\n    p.Age++\n\n}\n\nfunc main() {\n\n    Create a struct instance\n\n    person := Person{\n\n        Name: \"Zhang San\",\n\n        Age:  28,\n\n    }\n\n    \n\n    fmt. Println(person. Introduce()) \u002F\u002F call method\n\n    person. Grow() \u002F\u002F Age\n\n    fmt. Println(\"One year later:\", person. Introduce())\n\n}\n```\n\n### Interface\n\nThe interface defines a set of method signatures that implement the type of method that is \"implicit\" without the implementation details:\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\nDefining Interfaces (Method Collections)\n\ntype Speaker interface {\n\n    Speak() string\n\n}\n\nImplement type 1 of the interface\n\ntype Dog struct{}\n\nfunc (d Dog) Speak() string {\n\n    return \"Whoa\"\n\n}\n\nImplement type 2 of the interface\n\ntype Cat struct{}\n\nfunc (c Cat) Speak() string {\n\n    return \"Meow Meow\"\n\n}\n\nReceive interface type parameters\n\nfunc makeSound(s Speaker) {\n\n    fmt. Println(s.Speak())\n\n}\n\nfunc main() {\n\n    var animal Speaker\n\n    animal = Dog{}\n\n    makeSound(animal) \u002F\u002F Output: Wow\n\n    \n\n    animal = Cat{}\n\n    makeSound(animal) \u002F\u002F Output: Meow Meow Meow\n\n}\n```\n\nInterfaces are the core mechanism of the Go language to implement polymorphism, which greatly improves the flexibility and scalability of the code.\n\n## 6. Concurrent programming basics\n\nOne of the most important features of the Go language is the concurrency model, which enables lightweight concurrency through goroutines and channels:\n\n### Goroutine\n\nGoroutines are lightweight threads specific to the Go language, managed by the Go runtime, and are extremely cheap to create:\n\n\n\n```\npackage main\n\nimport (\n\n    \"fmt\"\n\n    \"time\"\n\n)\n\nFunctions that are executed concurrently\n\nfunc printNumbers() {\n\n    for i := 0; i \u003C 5; i++ {\n\n        time. Sleep(100 \\* time. Millisecond) \u002F\u002F Simulate time-consuming operations\n\n        fmt. Printf(\"%d \", i)\n\n    }\n\n}\n\nfunc printLetters() {\n\n    for c := 'a'; c \u003C 'f'; c++ {\n\n        time. Sleep(150 \\* time. Millisecond)\n\n        fmt. Printf(\"%c \", c)\n\n    }\n\n}\n\nfunc main() {\n\n    Start two goroutines (preceded by the go keyword)\n\n    go printNumbers()\n\n    go printLetters()\n\n    \n\n    The main goroutine waits for the sub-goroutine to complete (sync. WaitGroup）\n\n    time. Sleep(2 \\* time. Second)\n\n    fmt. Println(\"\\nEnd of Program\")\n\n}\n```\n\nRun results (in different order, reflecting concurrency):\n\n\n\n```\n0 a 1 b 2 c 3 d 4 e \n\nEnd of the procedure\n```\n\n### Channel\n\nChannel is used for communication between goroutines to achieve data synchronization:\n\n\n\n```\npackage main\n\nimport \"fmt\"\n\nSend data to the channel\n\nfunc sendData(ch chan\u003C- int) {\n\n    for i := 1; i \u003C= 5; i++ {\n\n        ch \u003C- i \u002F\u002F Send data to the channel\n\n    }\n\n    close(ch) \u002F\u002F Closes the channel\n\n}\n\nReceive data from the channel\n\nfunc receiveData(ch \u003C-chan int, done chan\u003C- bool) {\n\n    for num := range ch { \u002F\u002F loop until the channel is closed\n\n        fmt. Println(\"Received data:\", num)\n\n    }\n\n    done \u003C- true \u002F\u002F Notifies completion\n\n}\n\nfunc main() {\n\n    Create a channel (specify element type)\n\n    dataChan := make(chan int)\n\n    doneChan := make(chan bool)\n\n    \n\n    Start goroutine\n\n    go sendData(dataChan)\n\n    go receiveData(dataChan, doneChan)\n\n    \n\n    Wait for the receipt to complete\n\n    \u003C-doneChan\n\n    fmt. Println (\"All data processed\")\n\n}\n```\n\n## 7. Error handling\n\nThe Go language has no exception mechanism and explicitly handles errors by returning values:\n\n\n\n```\npackage main\n\nimport (\n\n    \"errors\"\n\n    \"fmt\"\n\n)\n\nReturns the wrong function\n\nfunc divide(a, b float64) (float64, error) {\n\n    if b == 0 {\n\n        Return a custom error\n\n        return 0, errors. New(\"Divisor cannot be zero\")\n\n    }\n\n    return a \u002F b, nil \u002F\u002F error nil when successful\n\n}\n\nfunc main() {\n\n    result, err := divide(10, 2)\n\n    if err != nil { \u002F\u002F Check for errors\n\n        fmt. Println(\"Error occurred:\", err)\n\n    } else {\n\n        fmt. Println(\"result:\", result)\n\n    }\n\n    \n\n    Examples of errors\n\n    result, err = divide(5, 0)\n\n    if err != nil {\n\n        fmt. Println(\"Error occurred:\", err)\n\n    }\n\n}\n```\n\n## 8. Summary and advanced direction\n\nThis article introduces the basic syntax of the Go language, including core concepts such as variable declarations, data types, control flows, functions, structs, interfaces, and concurrency. To truly master the Go language, you also need to study the following in depth:\n\n\n\n* Detailed explanation of standard libraries (common packages such as 'net\u002Fhttp' and 'encoding\u002Fjson')\n\n* Concurrency mode ('sync' package, goroutine pool, select statement)\n\n* Memory management and performance optimization\n\n* Testing & Performance Analysis ('Go Test', 'Pprof')\n\n* Actual project development (web service, tool development, etc.)\n\nThe Go language, with its simple and efficient characteristics, is particularly suitable for building high-performance backend services and cloud-native applications. Through continuous practice, you will gradually appreciate the unique charm of this language.\n\nFor further learning, you can visit [Go Official Documentation] (https:\u002F\u002Fgolang.org\u002Fdoc\u002F) or read classic books such as \"The Go Programming Language\".\n","go",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250716162537__暗夜雏菊.png",[15],"GO",false,{"id":18,"title":19,"title_en":20},13,"深入剖析 Go 语言中的 map","An in-depth look at maps in Go",{"id":22,"title":23,"title_en":24},15,"Vue3 + Go 实现第三方 OAuth 登录（GitHub , Microsoft）指南","Vue3 + Go Implement Third-Party OAuth Sign-in (GitHub, Microsoft) Complete Guide","2025-07-24T00:45:11+08:00"]