0

Is there a way to transform the match statement in the following code to the simplified 2018 edition syntax with automatic borrows?

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

This is what I tried, but the lifetime of the references were limited to the end of the match statement.

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wigy
  • 2,174
  • 19
  • 32
  • 2
    Remove every hint: `let x = match entry { Entry::Dir { mtime } | Entry::File { mtime, .. } => mtime };` – Shepmaster Mar 26 '19 at 17:07
  • 2
    Fixed title. Fixed grammar. Answered in a comment. And THEN closed as duplicate. You are my hero, @Shepmaster for all the service you are doing for the Rust community – wigy Mar 27 '19 at 08:28

0 Answers0