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:
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
}
}