Files
go-basics/stage01-basics/02-constants/main.go
T

100 lines
2.1 KiB
Go
Raw Normal View History

2026-03-13 23:54:07 +08:00
package main
import "fmt"
func exercise1() {
fmt.Println("=== 练习1:基本常量定义 ===")
// 使用const定义以下常量:
// GREETING: string,值为"你好,世界!"
// MAX_COUNT: int,值为1000
// SUCCESS: bool,值为true
const GREETING string = ____
const MAX_COUNT int = ____
const SUCCESS bool = ____
fmt.Printf("问候语: %s\n最大数量: %d\n成功状态: %t\n", GREETING, MAX_COUNT, SUCCESS)
}
func exercise2() {
fmt.Println("\n=== 练习2:批量常量定义 ===")
// 使用const块批量定义以下常量:
// HTTP_OK: int,值为200
// HTTP_NOT_FOUND: int,值为404
// HTTP_SERVER_ERROR: int,值为500
const (
HTTP_OK = ____
HTTP_NOT_FOUND = ____
HTTP_SERVER_ERROR = ____
)
fmt.Printf("HTTP状态码: OK=%d, NOT_FOUND=%d, SERVER_ERROR=%d\n",
HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR)
}
func exercise3() {
fmt.Println("\n=== 练习3:iota基础用法 ===")
// 使用iota定义一组连续的整数常量:
// SPRING: 0
// SUMMER: 1
// AUTUMN: 2
// WINTER: 3
// 提示:第一个使用 ioda = ioda,后续行省略
const (
SPRING = iota
SUMMER
AUTUMN
WINTER
)
fmt.Printf("季节常量: SPRING=%d, SUMMER=%d, AUTUMN=%d, WINTER=%d\n",
SPRING, SUMMER, AUTUMN, WINTER)
}
func exercise4() {
fmt.Println("\n=== 练习4:iota带表达式 ===")
// 使用iota定义从100开始的连续整数:
// LEVEL_1: 100
// LEVEL_2: 101
// LEVEL_3: 102
// LEVEL_4: 103
// 提示:第一个常量使用 ioda + 100
const (
LEVEL_1 = iota + ____
LEVEL_2
LEVEL_3
LEVEL_4
)
fmt.Printf("等级常量: LEVEL_1=%d, LEVEL_2=%d, LEVEL_3=%d, LEVEL_4=%d\n",
LEVEL_1, LEVEL_2, LEVEL_3, LEVEL_4)
}
func exercise5() {
fmt.Println("\n=== 练习5:iota位运算模式 ===")
// 使用iota和位移操作定义单位换算:
// KB: 1024 (1 << 10)
// MB: 1048576 (1 << 20)
// GB: 1073741824 (1 << 30)
const (
_ = iota
KB = 1 << ____
MB = 1 << ____
GB = 1 << ____
)
fmt.Printf("存储单位: KB=%d, MB=%d, GB=%d\n", KB, MB, GB)
}
func main() {
exercise1()
exercise2()
exercise3()
exercise4()
exercise5()
}