struct Person {
name: String,
age: i32,
choice: Choices
}
#[derive(Debug)]
enum Choices {
Good,
Neutral,
Evil
}
fn find(p: Person) {
match (p.choice, p.age) {
(Choices::Good, a) if a < 80 => {
announce(p);
}
(_, a) if a >= 80 => {
println!("You're too old to care.");
}
_ => {
println!("You're not very nice!")
}
}
}
fn announce(p: Person) {
println!("Your name is {}. You are {:?}.", p.name, p.choice);
}
fn main() {
let p = Person {
name: "Bob".to_string(),
age: 20,
choice: Choices::Good
};
find(p);
}
现在的问题似乎是在模式匹配过程中,移动语义会介入并接管我Person中的内部结构(Thing)。
当我试图将这个人传递给下一个方法时,由于已经部分移动,我无法这样做。
Compiling match v0.1.0 (file:///home/jocull/Documents/Projects/Rust/learn/match)
src/main.rs:17:13: 17:14 error: use of partially moved value: `p`
src/main.rs:17 announce(p);
^
src/main.rs:15:9: 15:17 note: `p.choice` moved here because it has type `Choices`, which is non-copyable
src/main.rs:15 match (p.choice, p.age) {
^~~~~~~~
error: aborting due to previous error
Could not compile `match`.
我的直觉告诉我,我需要通过使用引用或借用来阻止Rust移动该值。在这种情况下,我可以改变我的方法签名为借用,但是对于某些库,你并不总是能够这样做。(在这种情况下,我正在尝试处理hyper...)
有没有办法让
match
在匹配过程中使用引用而不是移动值?谢谢!