Files
go/std/func.md
2025-10-08 22:52:16 +08:00

116 lines
4.1 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

这个问题问得非常棒 👏,因为理解 **Go 的内置函数builtin functions** 是掌握这门语言的关键之一。
在 Go 里,“函数”可以分为三大类:
1.**内置函数built-in** —— 不需要导包,直接用;
2. 📦 **标准库函数** —— 比如 `math.*``fmt.*` 等;
3. 🧑‍💻 **用户自定义函数** —— 你自己写的。
---
## 🧩 一、内置函数Built-in Functions
这些是 Go 自带的核心函数,你可以在任何地方直接使用,不需要 `import`
| 函数 | 功能 |
| ----------------------------------------- | ------------------------------ |
| **append(slice, elems...)** | 向切片末尾添加元素,返回新切片 |
| **len(v)** | 返回长度适用于字符串、数组、切片、map、channel |
| **cap(v)** | 返回容量主要用于数组、切片、channel |
| **make(t, ...)** | 创建切片、map 或 channel |
| **new(T)** | 分配类型 `T` 的零值内存,返回指针 `*T` |
| **copy(dst, src)** | 将 `src` 拷贝到 `dst`,返回复制的元素数 |
| **delete(m, key)** | 从 map 中删除指定 key |
| **close(ch)** | 关闭一个 channel |
| **complex(r, i)** | 构造复数real + imag |
| **real(c)** | 获取复数的实部 |
| **imag(c)** | 获取复数的虚部 |
| **panic(v)** | 触发运行时错误,立刻中止程序 |
| **recover()** | 从 `panic` 中恢复(常在 `defer` 中使用) |
| **print(args...)** / **println(args...)** | 简单打印调试(不建议用于正式输出) |
---
### 🔍 举例:
```go
package main
import "fmt"
func main() {
// 1⃣ append
a := []int{1, 2}
a = append(a, 3, 4)
fmt.Println(a) // [1 2 3 4]
// 2⃣ len / cap
fmt.Println(len(a), cap(a)) // 4 4
// 3⃣ make
m := make(map[string]int)
m["Alice"] = 10
// 4⃣ delete
delete(m, "Alice")
// 5⃣ new
p := new(int)
*p = 42
fmt.Println(*p) // 42
// 6⃣ copy
b := make([]int, 2)
n := copy(b, a)
fmt.Println(b, n) // [1 2] 2
}
```
---
## 🧮 二、标准库函数(来自包)
这些需要 `import`,例如:
| 包 | 常用函数 |
| --------- | ----------------------------------------- |
| `fmt` | `Println`, `Printf`, `Sprintf` |
| `math` | `Pow`, `Sqrt`, `Sin`, `Cos`, `Abs` |
| `strings` | `Split`, `Join`, `Contains`, `ToUpper` |
| `strconv` | `Itoa`, `Atoi`, `ParseFloat`, `FormatInt` |
| `time` | `Now`, `Sleep`, `Since` |
| `sort` | `Sort`, `Ints`, `Strings` |
| `os` | `Open`, `Create`, `ReadFile`, `WriteFile` |
| `io` | `Copy`, `ReadAll` |
这些都不是语言级内置的,但在日常开发中使用频率极高。
---
## 🧑‍💻 三、你自己写的函数
```go
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add(3, 5)) // 8
}
```
---
### 🧠 小结对比:
| 类型 | 是否需 import | 示例 | 是否可重定义 |
| ----- | ---------- | ------------------------- | ------ |
| 内置函数 | ❌ | `len`, `append`, `make` | ❌ |
| 标准库函数 | ✅ | `math.Pow`, `fmt.Println` | ✅ |
| 自定义函数 | ✅ (你写的包) | `add`, `calc` | ✅ |
---
要不要我帮你整理一份「Go 内置函数的源码级行为图」?
能清晰看到 `make``new``append` 这些在底层是怎么运作的(内存分配、指针传递、是否返回新切片等)。