Lifetime of borrowed value error

"Getting borrowed value does not live long enough" error.

impl<'T> Input {
    fn new() ->Input {
        Input {
            value: RefCell::new("hello".to_string())
        }
    }

    fn update_value(&self, value: &str) {
        *self.value.borrow_mut() = value.to_string();
    }

    fn unescape_characters(&self) -> Box<dyn Any + 'T> {
        let borrowed_value = self.value.clone().into_inner();
        let val = match borrowed_value.as_str() {
            "\\" => "\\",
            "\\a" => "\x07",
            "\\b" => "\x08",
            "\\c" => return Box::new(true),
            "\\e" => "\x1b",
            "\\f" => "\x0c",
            "\\n" => "\n",
            "\\r" => "\r",
            "\\t" => "\t",
            "\\v" => "\x0b",
            _ => &borrowed_value
        };
        Box::new(val)
    }
}
error[E0597]: `borrowed_value` does not live long enough
  --> src/main.rs:39:18
   |
15 | impl<'T> Input {
   |      -- lifetime `'T` defined here
...
27 |         let borrowed_value = self.value.clone().into_inner();
   |             -------------- binding `borrowed_value` declared here
...
39 |             _ => &borrowed_value
   |                  ^^^^^^^^^^^^^^^ borrowed value does not live long enough
40 |         };
41 |         Box::new(val)
   |         ------------- cast requires that `borrowed_value` is borrowed for `'T`
42 |     }
   |     - `borrowed_value` dropped here while still borrowed
   |
   = note: due to object lifetime defaults, `Box<dyn Any>` actually means `Box<(dyn Any + 'static)>`


        let borrowed_value = self.value.clone().into_inner();
        let val = match borrowed_value.as_str() {
            // ...
        };
        Box::new(val)

You can never return a borrow of a local like borrowed_value, because all locals are dropped or otherwise moved by the time the function returns.

2 Likes

The borrowed_value variable has a bit misleading name, because clone() made it own the new cloned value.

So this is a new value that has been created inside the function, and will be destroyed when it goes out of scope, so you can't return loans into it. You need to return the whole object, or convert the substring to String or Box<str> so it's not borrowing.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.