std::panic::Location lifetime

Like in the examples in the doc of std::panic::Location my location has lifetime <'static>:

use derive_more::{Display, Error};
use std::panic::Location;
                                                            
#[derive(Debug, Error, Display)]
#[display("{}: {} at {}", label, cause, location)]
struct OneSizeFitsAll<'a> {
    cause: &'a str,
    location: Location<'static>,
    label: &'a str,
}

use OneSizeFitsAll as Fuba;

impl<'a> Fuba<'a> {
    #[track_caller]
    fn new(cause: &'a str, label: Option<&'a str>) -> Self {
        Self {
            cause,
            location: *Location::caller(),
            label: label.unwrap_or("Mother of all Errors"),
        }
    }
}

By chance I gave it the lifetime <‘a> and it works either.
Just a lucky punch or does it really not matter in this case?

Location::caller explicitly returns &'static Location<'static>, and Location is covariant, so Location<'static> can be assigned to any Location<'a>. Lifetime parameter is necessary when you use it during panic recovery, since it borrows from PanicInfo and can't outlive it, but with Location::caller everything is owned, not borrowed.

2 Likes

Reading helps. Thanks.