如何定义特征的可选方法?

How does one define optional methods on traits?

Rust 是否具有我可以在特征上创建定义可能不存在的方法的功能?

我意识到 Option 可用于处理可能不存在的属性,但我不知道如何使用方法实现相同的目的。

在 TypeScript 中,问号表示这些方法可能不存在。以下是 RxJs 的摘录:

export interface NextObserver<T> {
  next?: (value: T) => void;
  // ...
}

如果 Rust 中不存在此功能,那么应该如何考虑处理程序员不知道方法是否存在的对象?恐慌?

您可以尝试为此使用方法的空默认实现:

trait T {
    fn required_method(&self);

    // This default implementation does nothing        
    fn optional_method(&self) {}
}

struct A;

impl T for A {
    fn required_method(&self) {
        println!("A::required_method");
    }
}

struct B;

impl T for B {
    fn required_method(&self) {
        println!("B::required_method");
    }

    // overriding T::optional_method with something useful for B
    fn optional_method(&self) {
        println!("B::optional_method");
    }
}

fn main() {
    let a = A;
    a.required_method();
    a.optional_method(); // does nothing

    let b = B;
    b.required_method();
    b.optional_method();
}

Playground