by ww520 · 1y ago · 0 comments
A simple example using traits (Rust):
// logger.rs
trait Logger {
fn log_something(&self);
}
// mycustomlogger.rs
struct MyCustomLogger;
// logger.rs or mycustomlogger.rs
impl Logger for MyCustomLogger {
fn log_something(&self) {
println!("Hello");
}
}
The actual `log_something` implementation for `MyCustomLogger` (ie, the block with the `println!` call) can be outside of the impl, as a function or inherent method, and just be called by the impl block - thus implementing similar "glue" as described in the article.The difference is that there is no strong requirement on where exactly it needs to be [1].
This would likely require Zig to support "interfaces" at the language level, though.
--
[1] PS: there is the "orphan rule" for trait implementations, but I'm simplifying it here for the sake of the example
EDIT: formatting
The Zig version ‘Interface1.implBy(Impl2)’ is a rough equivalent to ‘impl Interface1 for Impl2’. It did it within the constraints of Zig.
Yes. It's not as crazy as you might imagine, and it's more robust than the log delegator approach.