我正在实现一个函数作为特征的一部分,如下所示:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何在 if 语句中生成错误实例。我已经尝试了以下所有方法,但都不起作用。编译器只是不高兴。
Err(Box::new(error::Error));
Err(Box::new(Error));
Err(Box::new(error::Error::new()));
Err(Box::new(error::Error::new("123")));
Run Code Online (Sandbox Code Playgroud)
我查看了文档,std::error::Error但在那里找不到答案。我是 Rust 新手,如果这很愚蠢,请原谅。
如果我有一些根本性的误解,请让我知道/指出我可以阅读的资源。
std::error::Error是一个特征,而不是一个类型,所以你不能直接创建它的实例。您需要选择一种实现该特征的现有类型(或编写一个新类型),然后使用它。
如果您只需要一条错误消息,您可以利用From<&str>for 实现Box<dyn Error>,并编写:
return Err(Box::from("your message here"));
Run Code Online (Sandbox Code Playgroud)
您也可以使用任何其他错误类型,例如std::io::Error:
use std::io;
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "your message here")));
Run Code Online (Sandbox Code Playgroud)