相关疑难解决方法(0)

如何使用相关类型的对象向量?

我有一个程序,涉及检查复杂的数据结构,看它是否有任何缺陷.(这很复杂,所以我发布了示例代码.)所有检查都是彼此无关的,并且都将拥有自己的模块和测试.

更重要的是,每个检查都有自己的错误类型,其中包含有关每个数字检查失败方式的不同信息.我这样做而不是只返回一个错误字符串,所以我可以测试错误(这就是为什么Error依赖PartialEq).

我的代码到目前为止

我有特点CheckError:

trait Check {
    type Error;
    fn check_number(&self, number: i32) -> Option<Self::Error>;
}

trait Error: std::fmt::Debug + PartialEq {
    fn description(&self) -> String;
}
Run Code Online (Sandbox Code Playgroud)

两个示例检查,带有错误结构.在此示例中,如果数字为负数或偶数,我想显示错误:


#[derive(PartialEq, Debug)]
struct EvenError {
    number: i32,
}
struct EvenCheck;

impl Check for EvenCheck {
    type Error = EvenError;

    fn check_number(&self, number: i32) -> Option<EvenError> {
        if number < 0 {
            Some(EvenError { number: number })
        } else {
            None
        }
    }
}

impl …
Run Code Online (Sandbox Code Playgroud)

collections types rust

11
推荐指数
2
解决办法
2640
查看次数

如何调用在盒装特征对象上消耗self的方法?

我有一个实现的草图:

trait Listener {
    fn some_action(&mut self);
    fn commit(self);
}

struct FooListener {}

impl Listener for FooListener {
    fn some_action(&mut self) {
        println!("{:?}", "Action!!");
    }

    fn commit(self) {
        println!("{:?}", "Commit");
    }
}

struct Transaction {
    listeners: Vec<Box<Listener>>,
}

impl Transaction {
    fn commit(self) {
        // How would I consume the listeners and call commit() on each of them?
    }
}

fn listener() {
    let transaction = Transaction {
        listeners: vec![Box::new(FooListener {})],
    };
    transaction.commit();
}
Run Code Online (Sandbox Code Playgroud)

我可以Transaction在它们上面使用侦听器,当事务发生时会调用侦听器.既然Listener是特质,我会存储一个Vec<Box<Listener>> …

ownership-semantics rust

10
推荐指数
2
解决办法
1330
查看次数

标签 统计

rust ×2

collections ×1

ownership-semantics ×1

types ×1