哈喽,又来发帖啦!这次给大家带来的是 rust 错误处理核心机制 的 ruby 实现。
本着 better ruby 的初心,我又去 rust 取了取经。
rust 的 Option 和 Result 类型由 enum 和泛型实现,ruby 没有确切对应的类型和泛型支持。
关于 rust match 的模式匹配,ruby 语法上比较接近的是 Data 类型,在 ruby 3.2 引入。
鉴于对 ruby 2.7 的兼容支持,我使用最简单的 class 实现这两者。
Bring the Rust [Result Option] type to Ruby
Install the gem and add to the application's Gemfile by executing:
bundle add rs-result
If bundler is not being used to manage dependencies, install the gem by executing:
gem install rs-result
require "rs/result"
x = Some.new(2)
x = None.new
x = Ok.new(-3)
x = Err.new("Some error message")
spec 测试 完全参考 rust 文档 及源码实现,一些 and or nor 等逻辑方法,引用可变方法,遍历迭代方法 我没有实现,也许更应该使用 ruby 的链式调用。
rust 的 这两种类型多用于 io 标准库,ruby 则多是 raise 抛出错误,语言本身不产生这种错误类型。
两种错误处理确实值得人深入思考,我在写库之余还学习了 rust,大善。
也希望大家可以多多尝试这个库,发现其中不足,给我一些反馈和意见,不胜感谢。