这个 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
的唯一方法。
最佳答案
一个常见的习惯用法是将项目作为 Result
的 Err
变体返回,或者嵌入其中(就像在 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/