How does one define optional methods on traits?
Asked Answered
H

1

11

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?

Hell answered 19/8, 2018 at 7:43 Comment(3)
In the way you describe it, no Rust don't have optional method. You should give a usecase where we can give you possible solution instead of trying to mimic something from an another language.Inhaler
"how should one think about dealing with objects whereby the programmer doesn't know whether a method will be present or not?", programmer is suppose to know if a method exist, maybe you want use dynamic load of function ?Inhaler
@Inhaler Thank you for your answer. Usecase: implementing the observer pattern in Rust in a similar way to rxjs likeso: github.com/ReactiveX/rxjs/blob/master/src/internal/types.ts#L56Hell
I
30

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

Idealize answered 19/8, 2018 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.