首页 > 解决方案 > 如何转换模式匹配以使用 Rust 2018 的自动借用?

问题描述

有没有办法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);
}

操场

这是我尝试过的,但引用的生命周期仅限于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

标签: rustpattern-matchingborrow-checker

解决方案


推荐阅读