package main
import (
"encoding/json"
"fmt"
"math"
"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),
}
}
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
type AreaOnly interface {
area() float64
}
type Rectangle struct {
width float64
height float64
}
func (r Rectangle) area() float64 {
return r.width * r.height
}
type SimpleCircle struct {
radius float64
}
func (c SimpleCircle) area() float64 {
return 3.14 * c.radius * c.radius
}
type Phone interface {
call() string
}
type NokiaPhone struct{}
func (n NokiaPhone) call() string {
return "I am Nokia, I can call you!"
}
type IPhone struct{}
func (i IPhone) call() string {
return "I am iPhone, I can call you!"
}
type Reader interface {
Read() string
}
type Writer interface {
Write(data string)
}
type ReadWriter interface {
Reader
Writer
}
type MemFile struct {
buf string
}
func (f *MemFile) Read() string {
return f.buf
}
func (f *MemFile) Write(data string) {
f.buf = data
}
func classifyType(val interface{}) string {
switch v := val.(type) {
case int:
return fmt.Sprintf("Integer: %d", v)
case string:
return fmt.Sprintf("String: %s", v)
case float64:
return fmt.Sprintf("Float: %.2f", v)
default:
return "Unknown type"
}
}
func main() {
var cases []Case
// Case 1: Implicit interface implementation & polymorphism
var s Shape = Circle{Radius: 5}
var p Phone
p = new(NokiaPhone)
nokiaCall := p.call()
p = new(IPhone)
iphoneCall := p.call()
var a AreaOnly
a = Rectangle{width: 10, height: 5}
rectArea := a.area()
a = SimpleCircle{radius: 3}
circArea := a.area()
actual1 := map[string]any{
"circle_area": fmt.Sprintf("%.6f", s.Area()),
"circle_perimeter": fmt.Sprintf("%.6f", s.Perimeter()),
"nokia": nokiaCall,
"iphone": iphoneCall,
"rect_area": fmt.Sprintf("%.2f", rectArea),
"simple_circ_area": fmt.Sprintf("%.2f", circArea),
}
expected1 := map[string]any{
"circle_area": "78.539816",
"circle_perimeter": "31.415927",
"nokia": "I am Nokia, I can call you!",
"iphone": "I am iPhone, I can call you!",
"rect_area": "50.00",
"simple_circ_area": "28.26",
}
cases = append(cases, makeCase(
"interface_shape_implicit_impl",
"核对隐式接口实现(Shape/Phone/AreaOnly)及同一接口变量存储不同结构体值的多态派发",
expected1, actual1,
))
// Case 2: Empty interface & dynamic type/value inspection
inputs := []interface{}{42, "hello", 3.14, []int{1, 2}}
var formatted []string
for _, val := range inputs {
formatted = append(formatted, fmt.Sprintf("Value: %v, Type: %T", val, val))
}
actual2 := map[string]any{"items": formatted}
expected2 := map[string]any{
"items": []string{
"Value: 42, Type: int",
"Value: hello, Type: string",
"Value: 3.14, Type: float64",
"Value: [1 2], Type: []int",
},
}
cases = append(cases, makeCase(
"interface_empty_and_dynamic_type",
"核对空接口 interface{} 存储多类型值时的动态类型 %T 与动态值 %v",
expected2, actual2,
))
// Case 3: Type assertions (direct, comma-ok, panic) & type switch
var iStr interface{} = "hello"
directStr := iStr.(string)
var iNum interface{} = 42
checkedStr, checkedOk := iNum.(string)
panicCaught := false
func() {
defer func() {
if r := recover(); r != nil {
panicCaught = strings.Contains(fmt.Sprint(r), "interface conversion")
}
}()
_ = iNum.(string)
}()
actual3 := map[string]any{
"direct_str": directStr,
"checked_str": checkedStr,
"checked_ok": checkedOk,
"panic_caught": panicCaught,
"switch_outs": []string{
classifyType(42),
classifyType("hello"),
classifyType(3.14),
classifyType([]int{1, 2, 3}),
},
}
expected3 := map[string]any{
"direct_str": "hello",
"checked_str": "",
"checked_ok": false,
"panic_caught": true,
"switch_outs": []string{
"Integer: 42",
"String: hello",
"Float: 3.14",
"Unknown type",
},
}
cases = append(cases, makeCase(
"interface_assertions_and_type_switch",
"核对直接类型断言、带检查类型断言(避免 panic)与 type switch 多分支分发",
expected3, actual3,
))
// Case 4: Interface composition (ReadWriter)
var rw ReadWriter = &MemFile{}
rw.Write("Hello, Go!")
actual4 := map[string]any{
"read_back": rw.Read(),
}
expected4 := map[string]any{
"read_back": "Hello, Go!",
}
cases = append(cases, makeCase(
"interface_composition_readwriter",
"核对嵌套组合接口 ReadWriter 同时提供 Reader 与 Writer 行为契约",
expected4, actual4,
))
// Case 5: Zero-value nil interface vs typed-nil interface
var nilIface interface{}
var typedNilPtr *Circle = nil
var shapeHoldingTypedNil Shape = typedNilPtr
actual5 := map[string]any{
"nil_iface_is_nil": nilIface == nil,
"typed_nil_iface_is_nil": shapeHoldingTypedNil == nil,
"typed_nil_dynamic_type": fmt.Sprintf("%T", shapeHoldingTypedNil),
}
expected5 := map[string]any{
"nil_iface_is_nil": true,
"typed_nil_iface_is_nil": false,
"typed_nil_dynamic_type": "*main.Circle",
}
cases = append(cases, makeCase(
"interface_nil_vs_typed_nil",
"核对未初始化零值接口为 nil,而包含具名空指针的接口因动态类型非空故 != nil",
expected5, actual5,
))
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-interfaces-lab/explore_interfaces.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_interfaces.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1172.zip