post/2024/05/24/interface-idioms/ #33
Replies: 1 comment 1 reply
-
文章写作不易,但实话实说:写得不是很直观,不如标准库里的代码清晰。 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
post/2024/05/24/interface-idioms/
原文链接: https://zig.news/yglcode/code-study-interface-idiomspatterns-in-zig-standard-libraries-4lkj
引言 在 Java 和 Go 中,可以使用“接口”(一组方法或方法集)定义基于行为的抽象。通常接口包含所谓的虚表(vtable) 以实现动态分派。Zig 允许在结构体、枚举、联合和不透明类型中声明函数和方法,尽管 Zig 尚未支持接口作为一种语言特性。 Zig 标准库应用了一些代码习语或模式以达到类似效果。
类似于其他语言中的接口,Zig 的代码习语和模式实现了:
在编译时对实例/对象方法与接口类型进行类型检查, 在运行时进行动态分派。 这里有一些显著的不同:
在 Go 中,接口的定义与实现是独立的。可以在任何位置给一个类型实现新接口,只需保证其方法签名与新接口一致即可。无需像在 Java 中那样,需要回过头去修改类型定义,来实现新的接口。 Go 的接口只包含用于动态分派的 vtab,并且推荐 vtable 中方法即可能少 ,例如 io.Reader 和 io.Writer只有一个方法。 常见的工具函数如io.Copy、CopyN、ReadFull、ReadAtLeast 等,作为包函数提供,内部使用这些小接口。 与之相比,Zig 的接口,如 std.mem.Allocator,同时包含 vtable 和一些工具方法,因此方法会多一些。 以下是 Zig 的代码习语/模式在动态分派方面的学习笔记,代码摘自 Zig 标准库并以简单示例重录。为了专注于 vtab/动态分派,工具方法被移除, 代码稍作修改以适应 Go 中不依赖具体类型的“小”接口模式。
完整代码位于此仓库,你可以使用 zig test interfaces.zig 运行它。
背景设定 让我们使用经典的面向对象编程示例,创建一些形状:点(Point)、盒子(Box)和圆(Circle)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 const Point = struct { x: i32 = 0, y: i32 = 0, pub fn move(self: *Point, dx: i32, dy: i32) void { self.
https://ziglang.cc/post/2024/05/24/interface-idioms/
Beta Was this translation helpful? Give feedback.
All reactions