在 Swift 中,我可以将扩展方法附加到任何struct,enum或protocol(与traitRust 中相同)。
protocol Foo1 {
func method1() -> Int
}
extension Foo1 {
func method2() {
print("\(method1())")
}
}
Run Code Online (Sandbox Code Playgroud)
那么Foo1现在所有符合协议的类型都有method2(). 这对于轻松构建“方法链”非常有用。
如何在 Rust 中做同样的事情?这对错误不起作用。
struct Kaz {}
impl Foo for Kaz {}
trait Foo {
fn sample1(&self) -> isize { 111 }
}
impl Foo {
fn sample2(&self) {
println!("{}", self.sample1());
}
}
fn main() {
let x = Kaz {};
x.sample1();
x.sample2();
}
Run Code Online (Sandbox Code Playgroud)
这是错误。
warning: …Run Code Online (Sandbox Code Playgroud)