rust - 如果方法失败,有没有办法将参数返回给调用者,而不是 panic ?

标签 rust

这个 impl 用于一个结构,该结构旨在保存卡片列表,但有一个可以添加到其中的卡片的最大数量:

trait Property {}

pub struct PropertySet {
    max: usize,
    properties: Vec<Box<dyn Property>>,
}

impl PropertySet {
    // ...

    /// This function will panic if a card is added and the set is already full, so
    /// you should always check the set size first.
    fn add<T: Property>(&mut self, property: T) {
        if self.properties.len() + 1 < self.max {
            self.properties.push(Box::new(property))
        } else {
            panic!("The card could not be added to the set; it is full.")
        }
    }

    // ...
}

panic 似乎是对尝试将卡片添加到完整集合的错误的不必要的激烈 react ,所以我想返回一个 Err,但这会带来问题,因为此方法移动卡片card 必须按值传递,因为这是我可以将它添加到 Vec 的唯一方法。

最佳答案

一个常见的习惯用法是将项目作为 ResultErr 变体返回,或者嵌入其中(就像在 std::sync 中使用的那样: :Arc::try_unwrap,所以你可以这样做:

impl PropertySet {
    /// This function will panic if a card is added and the set is already full, so
    /// you should always check the set size first.
    fn add<T: Property>(&mut self, property: T) -> Result<(), T> {
        if self.properties.len() + 1 < self.max {
            self.properties.push(Box::new(property));
            Ok(())
        } else {
            Err(property)
        }
    }
}

如果你想用更多信息装饰错误,你可以使用一个小的enum,比如:

enum HandError<T: Property> {
    HandFull(T),
    InsufficientBet,
    // ...
}
fn add<T: Property>(&mut self, property: T) -> Result<(), HandError<T>> {
    // ...
    Err(HandError::HandFull(property))
    // ...
}

关于rust - 如果方法失败,有没有办法将参数返回给调用者,而不是 panic ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281376/

相关文章:

closures - 如何为闭包参数声明更高级别的生命周期?

xml - 使用 serde-xml-rs 反序列化 XML 会产生 Err(重复字段 `$value` )

pointers - 如何从指向成员的指针获取指向包含结构的指针?

rust - Rustup未被认可,但很粗糙-版本有效

macros - 在宏中构建枚举

rust - 我是否缺少某种心智模型或模式来适应需要更复杂字段的各种不可变形式的类型?

rust - Rust 中的 "item"是什么?

rust - 在结构中嵌入具有生命周期的变量

rust - 你如何在比赛中借用可变引用?

iterator - 我什么时候应该使用 `drain` 与 `into_iter` ?