系列: Go
go
70 行
· 更新于 2026-04-18
main.go
Go/part1-language/examples/05_control/main.go
// Demonstrates control flow: if, for (all forms), switch, defer, recover.
package main
import "fmt"
func classify(x int) string {
switch {
case x < 0:
return "negative"
case x == 0:
return "zero"
default:
return "positive"
}
}
func deferOrder() {
defer fmt.Println("A (runs last)")
defer fmt.Println("B")
defer fmt.Println("C (runs first)")
fmt.Println("body")
}
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from: %v", r)
}
}()
return a / b, nil
}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("classic", i)
}
n := 0
for n < 3 {
fmt.Println("while-style", n)
n++
}
nums := []int{10, 20, 30}
for i, v := range nums {
fmt.Println("range", i, v)
}
outer:
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if i*j > 6 {
fmt.Println("breaking out at", i, j)
break outer
}
}
}
for _, x := range []int{-3, 0, 7} {
fmt.Println(x, classify(x))
}
deferOrder()
if v, err := safeDivide(10, 0); err != nil {
fmt.Println("got err:", err)
} else {
fmt.Println("got value:", v)
}
}
相关文章
Go
go
更新于 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
阅读文章 →
Go
go
更新于 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
阅读文章 →
Go
go
更新于 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
阅读文章 →
Go
go
更新于 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
阅读文章 →
Go
go
更新于 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
阅读文章 →
Go
go
更新于 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
阅读文章 →