0

Here is a made up example that reproduce the issue:

struct Metro<'a> {
    stations: Vec<Station<'a>>,
    monuments: Vec<Monument>
}

struct Station<'a> {
    name: String,
    closest_monument: Option<&'a Monument>
}

struct Monument {
    monument_name: String
}

impl <'a> Metro<'a> {
    pub fn stations_monument_assigning(&'a mut self){
        // in real life do some check to pick the best monument instead of first one
        self.stations[0].closest_monument = self.monuments.get(0);
    }

    pub fn new_network(stations: Vec<Station<'a>>, monuments: Vec<Monument>) -> Self {
        let mut metro = Metro { stations, monuments };
        metro.stations_monument_assigning();
        metro
    }
}

Here the compiler Error:

   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing local variable `metro`
  --> src/lib.rs:24:9
   |
23 |         metro.stations_monument_assigning();
   |         ----------------------------------- `metro` is borrowed here
24 |         metro
   |         ^^^^^ returns a value referencing data owned by the current function

error[E0505]: cannot move out of `metro` because it is borrowed
  --> src/lib.rs:24:9
   |
15 | impl <'a> Metro<'a> {
   |       -- lifetime `'a` defined here
...
22 |         let mut metro = Metro { stations, monuments };
   |             --------- binding `metro` declared here
23 |         metro.stations_monument_assigning();
   |         ----------------------------------- borrow of `metro` occurs here
24 |         metro
   |         ^^^^^
   |         |
   |         move out of `metro` occurs here
   |         returning this value requires that `metro` is borrowed for `'a`

Some errors have detailed explanations: E0505, E0515.
For more information about an error, try `rustc --explain E0505`.
error: could not compile `playground` (lib) due to 2 previous errors

It seems like the borrow checker does not understand that the station is referencing some data owned by the same struct, and makes it impossible the lose the data.

I tried playing with lifetime, ownership but nothing fancy. I don't really know what to look for.

doud
  • 1

0 Answers0