Lobsters | 📄 原文链接 | 2026-10-24 收录

Zig 也可以有 trait:用 comptime 结构体当类型契约

来源:axelmagn.com — 2026-10-03

📋 概述

Zig 的多态只有两条路:不透明指针加虚表做运行时派发,或者 comptime 鸭子类型在编译期单态化。前者有类型契约但性能有损,后者快但契约只靠文档和约定。作者提出第三种做法:把 trait 定义成一个编译期返回的 struct,里面装着一组与该类型相关的函数,实例化时把具体实现塞进去。这样既有明确契约、LSP 能补全,编译器也能内联并展开循环。

🔑 核心要点

💡 金句

Traits are just bags of functions and types that tell the receiving function how to execute subtasks that it's not responsible for defining.
← 返回 Lobsters 首页