Return Result from trait

Hello,

I'm having a bit of trouble with Rust traits and I was hoping I could get some help from the community.

I want to create a trait with a function that returns a Result. The Result should be of the type Result<String, String> but this doesn't seem to be possible as the code I've implemented (below) gives the following error.

Would anyone be able to explain what I am doing wrong here?

Error

method do_something has an incompatible type for trait expected signature fn() -> Result<(), std::fmt::Error> found signature fn() -> Result<String, String>

Code

pub trait Operations {
    fn do_something() -> Result;
}

impl Operations for Node {
    fn do_something() -> Result<String, String> {
        // Do some stuff
    }
}

if you want all the implementors to return the same type, then you should change the return type of the trait definition to use an exact type, instead of just some (probably aliased) shorthand Result:

pub trait Operations {
-    fn do_something() -> Result;
+    fn do_something() -> Result<String, String>;
}

if you want each implementor to choose its own type, you can use associated types:

pub trait Operations {
    type Ok;
    type Err;
    fn do_something() -> Result<Self::Ok, Self::Err>;
}

impl Operations for Node {
    type Ok = String;
    type Err = String;
    fn do_something() -> Result<String, String> {
        // Do some stuff
    }
}

The implementation needs to follow the trait. Return Result<String, String> from the trait as well.

Thanks for the quick reply folks.

I've tried to return Result<String, String> from the trait (code below) but the compiler gives me this error.

error[E0107]: type alias takes 0 generic arguments but 2 generic arguments were supplied

pub trait Operations {
    fn do_something() -> Result<String, String>;
}

Why do you have an alias of Result ? Remove it.

Yeah that was it.