Skip to content
On this page

Option 3: exercises/options/options3.rs

题目

rust
// options3.rs
//
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let y: Option<Point> = Some(Point { x: 100, y: 200 });

    match y {
        Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
        _ => panic!("no match!"),
    }
    y; // Fix without deleting this line.
}

题目解析

编译器提供的信息如下:

txt
⚠️  Compiling of exercises/options/options3.rs failed! Please try again. Here's the output:
error[E0382]: use of partially moved value: `y`
  --> exercises/options/options3.rs:20:5
   |
17 |         Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
   |              - value partially moved here
...
20 |     y; // Fix without deleting this line.
   |     ^ value used here after partial move
   |
   = note: partial move occurs because value has type `Point`, which does not implement the `Copy` trait
help: borrow this binding in the pattern to avoid moving the value
   |
17 |         Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
   |              +++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.

编译器提示我们变量y已经转移所有权,所以最后一行返回有问题。

但是注释又提醒我们又不能删除最后一行。

同时编译器提醒我们在Some(p)这里修改为Some(ref p)

rust
fn main() {
    let y: Option<Point> = Some(Point { x: 100, y: 200 });

    match y {
        Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), 
        Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y), 
        _ => panic!("no match!"),
    }
    y; // Fix without deleting this line.
}

编译通过了。

我们查看Rust的文档Keyword ref,了解到在模式匹配期间,如果使用ref关键字,该值仅被借用,而不会发生Move。

笔记

  • 在模式匹配期间,如果使用ref关键字,该值仅被借用,而不会发生Move

&ref的区别:

  • &表示您的模式期望引用一个对象。 因此,& 是所述模式的一部分: &FooFoo 匹配不同的对象。
  • ref 表示您想要解开一个包装后的值的引用。不匹配: Foo(ref foo)Foo(foo)匹配相同的对象。

参考资料

Powered by VitePress