Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one define optional methods on traits?

Does Rust have a feature whereby I can create define potentially non-existent methods on traits?

I realize that Option can be used to handle potentially non-existent properties but I don't know how the same can be achieved with methods.

In TypeScript, the question mark denotes that the methods may potentially be non-existent. Here is an excerpt from RxJs:

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

If this feature does not exist in Rust, how should one think about dealing with objects whereby the programmer doesn't know whether a method will be present or not? Panic?

like image 503
Tom Avatar asked Aug 19 '18 07:08

Tom


1 Answers

You can try using empty default implementations of methods for this:

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

like image 159
ozkriff Avatar answered Nov 04 '22 23:11

ozkriff