我在实现自定义错误类型时收到以下错误:
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),
}
}
我做错了什么?我试着按照这些例子:
2条答案
按热度按时间llew8vvj1#
在你的MemtableError-enum中你使用了
std::io::error
which does not implementClone
,这就是错误消息所显示的,你也应该得到同样的错误消息。要解决这个问题,你可以从你的派生宏中删除
Clone
。或者你需要显式地在你的错误类型上实现克隆。但是这在当前的设置中不起作用,因为io::Error在内部使用了一个trait对象(Box<dyn Error + Send + Sync>
)。并且这个trait对象不能被克隆。参见这个issue。一个解决方案是把std::io::Error
和std::string::FromUtf8Error
放在一个Rc
或Arc
:要查看这是否是解决此问题的合理方法,我们需要更多地了解其余代码。
因此,最简单的修复方法是删除
Clone
。否则,请使用Rc
/Arc
。z3yyvxxp2#
发生错误的原因是您试图为
MemtableError
派生Clone
实现,但是std::io::Error
(MemtableError
可以存储的值的类型)本身并没有实现Clone
。如果不需要克隆,我会将其简单地更改为#[derive(Debug)]
。否则,我们需要您的用例的更多上下文来建议更具体的修复。