相关疑难解决方法(0)

Rust 相当于 Swift 对协议的扩展方法?

在 Swift 中,我可以将扩展方法附加到任何struct,enumprotocol(与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)

extension-methods traits rust

5
推荐指数
1
解决办法
1103
查看次数

标签 统计

extension-methods ×1

rust ×1

traits ×1