gpt4 book ai didi

enums - 特征绑定(bind) io::Error: Clone is not satisfied when implementing a custom error enum

转载 作者:行者123 更新时间:2023-12-05 02:58:07 24 4
gpt4 key购买 nike

我在实现自定义错误类型时收到以下错误:

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),
}
}

我做错了什么?我尝试按照这些示例进行操作:

  1. https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/define_error_type.html
  2. https://learning-rust.github.io/docs/e7.custom_error_types.html
  3. https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html

最佳答案

在你的 MemtableError 枚举中你使用 std::io::error它没有实现克隆。这就是错误消息所说的。您还应该得到关于 std::string::FromUtf8Error 的相同错误.

要解决此问题,您可以删除 Clone从你的派生宏。或者你需要在你的错误类型上显式地实现 Clone 。然而,这在当前设置中不起作用,因为 io::Error 在内部使用特征对象( Box<dyn Error + Send + Sync> )。而且这个特征对象不能被克隆。看这个issue .解决方法是将 std::io::Errorstd::string::FromUtf8ErrorRcArc :

#[derive(Debug, Clone)]
pub enum MemtableError {
Io(std::rc::Rc<io::Error>),
FromUTF8(std::rc::Rc<std::string::FromUtf8Error>),
NotFound,
}

要了解这是否是解决此问题的合理方法,我们需要更多地了解您的其余代码。

因此,最简单的解决方法是删除 Clone .否则使用 Rc/Arc .

关于enums - 特征绑定(bind) io::Error: Clone is not satisfied when implementing a custom error enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com