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

Tom*_*Tom 3 interface custom-type rust

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

我意识到这Option可以用来处理可能不存在的属性,但我不知道如何用方法实现相同.

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

export interface NextObserver<T> {
  next?: (value: T) => void;
  // ...
}
Run Code Online (Sandbox Code Playgroud)

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

ozk*_*iff 12

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

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();
}
Run Code Online (Sandbox Code Playgroud)

操场