I'm implementing a function as part of trait like so:
impl TryFrom<(i16, i16, i16)> for Color {
type Error = Box<dyn error::Error>;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if tuple.0 < 0 || tuple.1 < 0 || tuple.2 < 0 || tuple.0 > 255 || tuple.1 > 255 || tuple.2 >255 {
return Err(Box::new(error::Error)); //how do I generate an instance of an error?
}
let c = Self { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 };
Ok(c)
}
}
And I can't figure out how to generate an instance of an errror in the if statement. I've tried all of the below and none work. The compiler just isn't happy.
Err(Box::new(error::Error));
Err(Box::new(Error));
Err(Box::new(error::Error::new()));
Err(Box::new(error::Error::new("123")));
I've looked at docs for std::error::Error
but I can't find an answer there. I'm new to Rust so pardon if this is stupid.
If there's some fundamental misunderstanding on my part, please let me know / point to resources I can read.
std::error::Error
is a trait, not a type, so you cannot directly create an instance of it. You need to choose an existing type that implements the trait (or write a new one), and use that.
If you just need an error message, you can make use of From<&str>
being implemented for Box<dyn Error>
, and write:
return Err(Box::from("your message here"));
You can also use any concrete error type that implements the Error
trait, such as std::io::Error
:
return Err(Box::new(io::Error::other("your message here")));