实现自定义错误类型时,我收到以下错误:
the trait bound `std::io::Error: std::clone::Clone` is not satisfied
这是我的自定义错误枚举:
use std::fmt;
use std::io;
use crate::memtable::Memtable;
// Define our error types. These may be customized for our error handling cases.
// Now we will be able to write our own errors, defer to an underlying error
// implementation, or do something in between.
#[derive(Debug, Clone)]
pub enum MemtableError {
Io(io::Error),
FromUTF8(std::string::FromUtf8Error),
NotFound,
}
// Generation of an error is completely separate from how it is displayed.
// There's no need to be concerned about cluttering complex logic with the display style.
//
// Note that we don't store any extra info about the errors. This means we can't state
// which string failed to parse without modifying our types to carry that information.
impl fmt::Display for MemtableError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Some error occurred!");
Ok(())
}
}
// a test function that returns our error result
fn raises_my_error(memtable: Memtable, key: String) -> Result<(),MemtableError> {
match memtable.read(key) {
Ok(v) => Ok(()),
Err(e) => Err(e),
}
}
我在做什么错?我尝试了以下示例:
发生错误是因为您试图派生Clone
的MemtableError
实现,但是std::io::Error
(MemtableError
可以存储的值之一的类型)本身并未实现Clone
。如果不需要克隆,我将其更改为#[derive(Debug)]
。否则,我们将需要更多有关您的用例的上下文,以提出更具体的修复方法。
在您的MemtableError枚举中,您使用的std::io::error
未实现克隆。这就是错误消息的意思。您还应该获得关于std::string::FromUtf8Error
的相同错误。
要解决此问题,您可以从派生宏中删除Clone
。或者您需要在错误类型上显式实现Clone。但是,这在当前设置中将不起作用,因为io :: Error在内部使用了特征对象(Box<dyn Error + Send + Sync>
)。并且无法克隆此特征对象。参见此issue。一种解决方法是将std::io::Error
和std::string::FromUtf8Error
放在Rc
或Arc
中:
#[derive(Debug, Clone)]
pub enum MemtableError {
Io(std::rc::Rc<io::Error>),
FromUTF8(std::rc::Rc<std::string::FromUtf8Error>),
NotFound,
}
要查看这是否是解决此问题的合理方法,我们需要更多地了解其余代码。
因此,最简单的解决方法是删除Clone
。否则,请使用Rc
/ Arc
。