package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
"runtime"
)
type CaseResult struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type LabOutput struct {
Version string `json:"version"`
Cases []CaseResult `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) CaseResult {
return CaseResult{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
func main() {
var cases []CaseResult
// 1. for_loop_and_nested_for
sum := 0
for i := 1; i <= 5; i++ {
sum += i
}
var pairs []string
for r := 1; r <= 2; r++ {
for c := 1; c <= 3; c++ {
pairs = append(pairs, fmt.Sprintf("%dx%d=%d", r, c, r*c))
}
}
cases = append(cases, makeCase(
"for_loop_and_nested_for",
"验证基础 for 累加循环与两层嵌套 for 乘积表遍历",
map[string]any{
"sum_1_to_5": 15,
"grid": []string{"1x1=1", "1x2=2", "1x3=3", "2x1=2", "2x2=4", "2x3=6"},
},
map[string]any{
"sum_1_to_5": sum,
"grid": pairs,
},
))
// 2. break_and_continue_control
var odds []int
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
if i > 7 {
break
}
odds = append(odds, i)
}
var stopCell string
Outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 2 {
stopCell = fmt.Sprintf("%d,%d", i, j)
break Outer
}
}
}
cases = append(cases, makeCase(
"break_and_continue_control",
"验证 continue 跳过偶数、break 提前终止以及带标签 break 跳出外层嵌套循环",
map[string]any{
"odds_upto_7": []int{1, 3, 5, 7},
"label_break": "1,2",
},
map[string]any{
"odds_upto_7": odds,
"label_break": stopCell,
},
))
// 3. goto_label_control
var visited []int
a := 10
Loop:
for a < 15 {
if a == 12 {
a++
goto Loop
}
visited = append(visited, a)
a++
}
cases = append(cases, makeCase(
"goto_label_control",
"验证 goto 跳转至 Loop 标签跳过 a==12 的迭代",
[]int{10, 11, 13, 14},
visited,
))
// 4. infinite_loop_with_break_guard
var ticks []string
count := 0
for true {
count++
ticks = append(ticks, fmt.Sprintf("第%d轮", count))
if count >= 3 {
break
}
}
cases = append(cases, makeCase(
"infinite_loop_with_break_guard",
"验证 for true 无限循环结构在显式退出条件触发 break 后安全结束",
[]string{"第1轮", "第2轮", "第3轮"},
ticks,
))
out := LabOutput{
Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Cases: cases,
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(out); err != nil {
panic(err)
}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。
入口文件:projects/go-loops-lab/explore_loops.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_loops.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1174.zip