package main
import (
"bytes"
"encoding/json"
"fmt"
"go/scanner"
"go/token"
"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 addInts(a, b int) int {
return a + b
}
func main() {
var cases []CaseResult
// 1. go_scanner_tokens
stmt := []byte(`fmt.Println("Hello, World!")`)
fset := token.NewFileSet()
file := fset.AddFile("stmt.go", fset.Base(), len(stmt))
var s scanner.Scanner
s.Init(file, stmt, nil, 0)
var toks []string
for {
_, tok, lit := s.Scan()
if tok == token.EOF {
break
}
if tok == token.SEMICOLON {
continue
}
if lit != "" {
toks = append(toks, lit)
} else {
toks = append(toks, tok.String())
}
}
cases = append(cases, makeCase(
"go_scanner_tokens",
"使用 go/scanner 切分 fmt.Println(\"Hello, World!\") 为 6 个词法标记",
[]string{"fmt", ".", "Println", "(", `"Hello, World!"`, ")"},
toks,
))
// 2. line_separator_and_comments
twoLines := []byte("// 单行注释\n/* 多行注释 */\nfmt.Println(\"A\")\nfmt.Println(\"B\")\n")
fset2 := token.NewFileSet()
file2 := fset2.AddFile("lines.go", fset2.Base(), len(twoLines))
var s2 scanner.Scanner
s2.Init(file2, twoLines, nil, 0) // 0 mode ignores comments
semiCount := 0
commentCount := 0
for {
_, tok, _ := s2.Scan()
if tok == token.EOF {
break
}
if tok == token.SEMICOLON {
semiCount++
}
if tok == token.COMMENT {
commentCount++
}
}
// Explicit semicolon on one line also executes cleanly
var oneLineBuf bytes.Buffer
fmt.Fprint(&oneLineBuf, "A"); fmt.Fprint(&oneLineBuf, "B")
cases = append(cases, makeCase(
"line_separator_and_comments",
"验证行尾自动插入分号、单行与多行注释被编译器忽略以及同行显式分号分隔",
map[string]any{
"auto_semicolons": 2,
"compiled_comments": 0,
"same_line_output": "AB",
},
map[string]any{
"auto_semicolons": semiCount,
"compiled_comments": commentCount,
"same_line_output": oneLineBuf.String(),
},
))
// 3. identifier_validation
validNames := []string{"mahesh", "kumar", "abc", "move_name", "a_123", "myname50", "_temp", "j", "a23b9", "retVal"}
invalidNames := []string{"1ab", "case", "a+b"}
allValidOK := true
for _, id := range validNames {
if !token.IsIdentifier(id) || token.IsKeyword(id) {
allValidOK = false
}
}
invalidChecks := make(map[string]bool)
for _, id := range invalidNames {
invalidChecks[id] = token.IsIdentifier(id) && !token.IsKeyword(id)
}
cases = append(cases, makeCase(
"identifier_validation",
"使用 go/token 校验合法标识符集合与数字开头/关键字/运算符等非法标识符",
map[string]any{
"all_10_valid_ok": true,
"1ab": false,
"case": false,
"a+b": false,
},
map[string]any{
"all_10_valid_ok": allValidOK,
"1ab": invalidChecks["1ab"],
"case": invalidChecks["case"],
"a+b": invalidChecks["a+b"],
},
))
// 4. string_concat_and_whitespace
var x int = 5
const Pi float64 = 3.14159265358979323846
apples, oranges := 3, 4
fruit := apples + oranges
gtZero := false
if x > 0 {
gtZero = true
}
result := addInts(2, 3)
cases = append(cases, makeCase(
"string_concat_and_whitespace",
"验证字符串 + 拼接以及声明、运算符、条件与函数调用中的规范空格写法",
map[string]any{
"concat": "GoLanguage",
"pi_gt_3": true,
"fruit": 7,
"gt_zero": true,
"call_sum": 5,
},
map[string]any{
"concat": "Go" + "Language",
"pi_gt_3": Pi > 3.14,
"fruit": fruit,
"gt_zero": gtZero,
"call_sum": result,
},
))
// 5. keywords_and_predeclared_identifiers
keywords := []string{
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var",
}
kwCount := 0
for _, kw := range keywords {
if token.IsKeyword(kw) {
kwCount++
}
}
predeclared := []string{
"append", "bool", "byte", "cap", "close", "complex", "complex64", "complex128", "uint16",
"copy", "false", "float32", "float64", "imag", "int", "int8", "int16", "uint32",
"int32", "int64", "iota", "len", "make", "new", "nil", "panic", "uint64",
"print", "println", "real", "recover", "string", "true", "uint", "uint8", "uintptr",
}
preOK := 0
for _, p := range predeclared {
if token.IsIdentifier(p) && !token.IsKeyword(p) {
preOK++
}
}
cVal := complex(3.0, 4.0)
sl := make([]int, 0, 4)
sl = append(sl, 10, 20)
cases = append(cases, makeCase(
"keywords_and_predeclared_identifiers",
"校验全部 25 个 Go 关键字与 36 个经典预定义标识符分类及内置函数行为",
map[string]any{
"keyword_count": 25,
"predeclared_count": 36,
"slice_len_cap": []int{2, 4},
"complex_real_imag": []float64{3.0, 4.0},
},
map[string]any{
"keyword_count": kwCount,
"predeclared_count": preOK,
"slice_len_cap": []int{len(sl), cap(sl)},
"complex_real_imag": []float64{real(cVal), imag(cVal)},
},
))
// 6. sprintf_and_printf_formatting
stockcode := 123
enddate := "2020-12-31"
urlPattern := "Code=%d&endDate=%s"
targetURL := fmt.Sprintf(urlPattern, stockcode, enddate)
var pbuf bytes.Buffer
fmt.Fprintf(&pbuf, urlPattern, stockcode, enddate)
cases = append(cases, makeCase(
"sprintf_and_printf_formatting",
"验证 fmt.Sprintf 返回格式化字符串与 fmt.Printf/Fprintf 输出结果一致",
map[string]any{
"sprintf": "Code=123&endDate=2020-12-31",
"printf": "Code=123&endDate=2020-12-31",
},
map[string]any{
"sprintf": targetURL,
"printf": pbuf.String(),
},
))
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-basic-syntax-lab/explore_basic_syntax.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_basic_syntax.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1160.zip