Stream: t-compiler/help

Topic: 'static life time


Derek (May 24 2020 at 18:48, on Zulip):

I'm saw some library, there are some function return value with 'static lifetime annotation. initially I thought in this case it will be dropped at end of main. but actually it get dropped early than that. e.g. here is the simplified one. here is code on playground.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8dc767d333df5a812ffae87e9fc28c29
the output is

[1, 2, 3, 4]
dropped
end consume
end main

instead of.

[1, 2, 3, 4]
end consume
end main
dropped

My question is why need 'static lifetime annotation in return value for Block. I thought the output "dropped" will be at the end of the main.
but seems I don't understand 'static lifetime correctly. can someone explain? Thanks.

use std::borrow::Cow;
use std::fmt;

pub struct Block<'a> {
    pub body: Cow<'a, [u8]>,
}
impl<'a> fmt::Debug for Block<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.body)
    }
}
impl<'a> Drop for Block<'a> {
    fn drop(&mut self) {
        println!("dropped");
    }
}
fn get_block() -> Block<'static> {
    let v = vec![1,2,3,4];
    Block {
        body: Cow::Owned(v),
    }
}
fn consume() {
    {
        let b = get_block();
        println!("{:?}", b);
    }
    println!("end consume");
}

fn main() {
  consume();
  println!("end main");
}
bjorn3 (May 24 2020 at 18:55, on Zulip):

A lifetime provides an upper bound that a type can live for. It doesn't say that it lives for exactly that long. In this case Block<'static> can live for as long as you want it to live before you drop it. You can decide to drop it at any point in time that there is no active reference to it. In this case it gets dropped as b gets out of scope.

Last update: Sep 28 2020 at 15:00UTC