如何使火柴臂识别数值参数



我正试图根据关联函数中传递的值交换结构的内容。然而,在使用match时,arm似乎无法识别值参数,因此第一个参数之后的arm变得不可访问。

#[derive(Debug, Copy, Clone)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Color {
pub fn swap(mut self, first: u8, second: u8) -> Color {
let mut swapped = self;
match self {
Color { r: first, g, b, a } => swapped.r = second,
Color { r, g: first, b, a } => swapped.g = second,
Color { r, g, b: first, a } => swapped.b = second,
Color { r, b, g, a: first } => swapped.a = second,
}
match self {
Color { r: second, g, b, a } => swapped.r = first,
Color { r, g: second, b, a } => swapped.g = first,
Color { r, g, b: second, a } => swapped.b = first,
Color { r, g, b, a: second } => swapped.a = first,
}
self = swapped;
self
}
}

然而,如果我放一个像Color { r: 10, g,b,a }这样的实际u8,那么它就可以工作了。

我在这里做错了什么?

您正在创建一个新的first绑定,并销毁Color。要进行变量值比较,您需要一个";火柴卫士";像这样:

match self {
Color { r, g, b, a } if r == first => swapped.r = second,
Color { r, g, b, a } if g == first => swapped.g = second,
Color { r, g, b, a } if b == first => swapped.b = second,
Color { r, b, g, a } if a == first => swapped.a = second,
_ => { /* no match */ },
}

最后的";全部匹配";arm是必需的,因为模式是非穷尽的,所以您需要告诉Rust在其他arm的none匹配的情况下该怎么办。例如,可以在此处恐慌以发出错误输入信号,或者修改函数以从match-all arm返回Result<Color, SomeErrorType>Err

注意,由于每个手臂只使用一个字段,因此可以忽略其他字段:

match self {
Color { r, .. } if r == first => swapped.r = second,
Color { g, .. } if g == first => swapped.g = second,
Color { b, .. } if b == first => swapped.b = second,
Color { a, .. } if a == first => swapped.a = second,
_ => { /* no match */ },
}

最新更新