如何转换模式匹配以使用Rust 2018的自动借用?

时间:2019-03-26 17:02:13

标签: rust pattern-matching borrow-checker

是否可以将以下代码中的match语句转换为带有自动借位的简化的2018版语法?

enum Entry {
    Dir { mtime: i64 },
    File { mtime: i64, _size: u64 },
}

fn touch(entry: &mut Entry, mtime: i64) {
    let x: &mut i64 = match *entry {
        Entry::Dir { ref mut mtime } => mtime,
        Entry::File { ref mut mtime, .. } => mtime,
    };
    *x = mtime;
}

fn main() {
    let mut entry1 = Entry::Dir { mtime: 0 };
    touch(&mut entry1, 1);

    let mut entry2 = Entry::File {
        mtime: 0,
        _size: 1024,
    };
    touch(&mut entry2, 1);
}

Playground

这是我尝试过的方法,但是引用的生存期仅限于match语句的结尾。

let x: &mut i64 = match entry {
    Entry::Dir { mut mtime } => &mut mtime,
    Entry::File { mut mtime, .. } => &mut mtime,
};
error[E0597]: `mtime` does not live long enough
  --> src/main.rs:8:37
   |
7  |     let x: &mut i64 = match entry {
   |         - borrow later stored here
8  |         Entry::Dir { mut mtime } => &mut mtime,
   |                                     ^^^^^^^^^^ borrowed value does not live long enough
9  |         Entry::File { mut mtime, .. } => &mut mtime,
10 |     };
   |     - `mtime` dropped here while still borrowed

0 个答案:

没有答案