package main
import (
"encoding/json"
"fmt"
"io"
"os"
"reflect"
"runtime"
"strings"
)
type Case struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type Report struct {
Version string `json:"version"`
Cases []Case `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) Case {
return Case{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
func describeByTypeSwitch(i interface{}) string {
switch v := i.(type) {
case nil:
return "nil"
case int:
return fmt.Sprintf("int:%d", v)
case string:
return fmt.Sprintf("string:%s", v)
default:
return "unknown"
}
}
func processInterface(i interface{}) string {
if s, ok := i.(string); ok {
return "str:" + s
} else if n, ok := i.(int); ok {
return fmt.Sprintf("int:%d", n)
}
return "unsupported"
}
func main() {
var cases []Case
// Case 1: Comma-ok safe type assertion
var i interface{} = "Hello, Go!"
sVal, sOk := i.(string)
nVal, nOk := i.(int)
var nilIface interface{}
nilStr, nilOk := nilIface.(string)
actual1 := map[string]any{
"str_val": sVal,
"str_ok": sOk,
"int_val": nVal,
"int_ok": nOk,
"nil_val": nilStr,
"nil_ok": nilOk,
}
expected1 := map[string]any{
"str_val": "Hello, Go!",
"str_ok": true,
"int_val": 0,
"int_ok": false,
"nil_val": "",
"nil_ok": false,
}
cases = append(cases, makeCase(
"assertion_comma_ok_safe",
"核对带 ok 布尔返回的安全类型断言:成功返回实际值、失败返回零值与 false 不触发 panic",
expected1, actual1,
))
// Case 2: Single-value assertion & panic recovery
directStr := i.(string)
panicMsg := ""
func() {
defer func() {
if r := recover(); r != nil {
panicMsg = fmt.Sprint(r)
}
}()
_ = i.(int)
}()
actual2 := map[string]any{
"direct_str": directStr,
"panic_contains_msg": strings.Contains(panicMsg, "interface conversion: interface {} is string, not int"),
}
expected2 := map[string]any{
"direct_str": "Hello, Go!",
"panic_contains_msg": true,
}
cases = append(cases, makeCase(
"assertion_single_value_and_panic",
"核对单返回值类型断言成功与失败触发 interface conversion panic 行为",
expected2, actual2,
))
// Case 3: Type switch
actual3 := map[string]any{
"int_out": describeByTypeSwitch(42),
"string_out": describeByTypeSwitch("Go"),
"default_out": describeByTypeSwitch(true),
"nil_out": describeByTypeSwitch(nil),
}
expected3 := map[string]any{
"int_out": "int:42",
"string_out": "string:Go",
"default_out": "unknown",
"nil_out": "nil",
}
cases = append(cases, makeCase(
"assertion_type_switch",
"核对 switch v := i.(type) 对多种具体类型、default 及 nil 分支的匹配",
expected3, actual3,
))
// Case 4: Extracting concrete type & interface-to-interface assertion
var r io.Reader = strings.NewReader("abcdef")
seeker, isSeeker := r.(io.Seeker)
pos, _ := seeker.Seek(2, io.SeekStart)
rest, _ := io.ReadAll(r)
actual4 := map[string]any{
"proc_str": processInterface("text"),
"proc_int": processInterface(99),
"proc_other": processInterface(3.14),
"is_seeker": isSeeker,
"seek_pos": int(pos),
"after_seek": string(rest),
}
expected4 := map[string]any{
"proc_str": "str:text",
"proc_int": "int:99",
"proc_other": "unsupported",
"is_seeker": true,
"seek_pos": 2,
"after_seek": "cdef",
}
cases = append(cases, makeCase(
"assertion_extract_concrete_interface",
"核对条件链提取接口底层具体类型以及接口到可选扩展接口(io.Reader -> io.Seeker)的断言",
expected4, actual4,
))
report := Report{
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(report); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
本例需在 本地离线 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-type-assertion-lab/explore_type-assertion.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_type-assertion.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1188.zip