Skip to content

Instantly share code, notes, and snippets.

@maikwoehl
Created May 19, 2020 22:08
Show Gist options
  • Save maikwoehl/62f9eb7b307548f31fe438ed881c9100 to your computer and use it in GitHub Desktop.
Save maikwoehl/62f9eb7b307548f31fe438ed881c9100 to your computer and use it in GitHub Desktop.
This gist shows, why the lifetime specifier helps the rust compiler to see a hidden borrow.
enum Quality {
Good,
Questionable,
Invalid,
}
// TODO: Implement as trait
struct HasQuality<'a> {
pub value: &'a Box<&'a str>,
quality: Quality,
}
impl<'a> HasQuality<'a> {
pub fn new(value: &'a Box<&'a str>, quality: Quality) -> Self {
Self {
value,
quality,
}
}
}
impl<'a> Drop for HasQuality<'a> {
fn drop(&mut self) { }
}
#[test]
fn it_works() {
let message = Box::new("Hello World!");
let information = HasQuality::new(&message, Quality::Good);
assert_eq!(*information.value, Box::new("Hello World!"));
drop(message);
assert_eq!(*information.value, Box::new("Hello World!"));
drop(information);
assert_eq!(*information.value, Box::new("Hello World!"));
}
/// OUTPUT:
/// ```
/// error[E0505]: cannot move out of `message` because it is borrowed
/// --> src/lib.rs:29:10
/// |
/// 27 | let information = HasQuality::new(&message, Quality::Good);
/// | -------- borrow of `message` occurs here
/// 28 | assert_eq!(*information.value, Box::new("Hello World!"));
/// 29 | drop(message);
/// | ^^^^^^^ move out of `message` occurs here
/// 30 | assert_eq!(*information.value, Box::new("Hello World!"));
/// | --------------------------------------------------------- borrow later used here
///
/// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment