初始化

This commit is contained in:
2025-04-08 17:01:19 +08:00
commit 4228f447f7
75 changed files with 574 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
module definition
go 1.23.5

View File

@@ -0,0 +1,31 @@
package main
import "fmt"
// 基本函数定义
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
// 带返回值的函数
func add(a, b int) int {
return a + b
}
// 多返回值函数
func swap(x, y string) (string, string) {
return y, x
}
func main() {
// 调用无返回值函数
greet("Gopher")
// 调用单返回值函数
sum := add(3, 5)
fmt.Println("3 + 5 =", sum)
// 调用多返回值函数
a, b := swap("hello", "world")
fmt.Println(a, b)
}

View File

@@ -0,0 +1,3 @@
module multiple_returns
go 1.23.5

View File

@@ -0,0 +1,39 @@
package main
import (
"fmt"
"math"
)
// 返回计算结果和错误信息
func sqrt(x float64) (float64, error) {
if x < 0 {
return 0, fmt.Errorf("不能对负数 %f 开平方", x)
}
return math.Sqrt(x), nil
}
// 命名返回值
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // 裸返回
}
func main() {
// 处理多返回值
if result, err := sqrt(16); err != nil {
fmt.Println("错误:", err)
} else {
fmt.Println("平方根:", result)
}
// 处理错误情况
if _, err := sqrt(-4); err != nil {
fmt.Println("错误:", err)
}
// 使用命名返回值
a, b := split(17)
fmt.Printf("split(17) = %d, %d\n", a, b)
}

View File

@@ -0,0 +1,3 @@
module anonymous
go 1.23.5

View File

@@ -0,0 +1,34 @@
package main
import "fmt"
func main() {
// 立即执行的匿名函数
func(msg string) {
fmt.Println(msg)
}("立即执行的匿名函数")
// 将匿名函数赋值给变量
greet := func(name string) {
fmt.Printf("Hello, %s!\n", name)
}
greet("Gopher")
// 闭包示例
adder := func() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
// 使用闭包
pos, neg := adder(), adder()
for i := 0; i < 5; i++ {
fmt.Println(
"pos:", pos(i),
"neg:", neg(-2*i),
)
}
}