Set default value to a lifetime mark

As we all know , we can set a default type to a generic type.

#[derive(Debug, Error)]
struct Ce<'a, T = String> {
    err: &'a T,
}

But whether we can do the same thing to the lifetime ?

Just like this .

#[derive(Debug, Error)]
struct Ce<'a = 'static, T = String> {
    err: &'a T,
} 

But actually it can't be compiled .

you cannot, common workaround is to use type aliases. if you don't want to introduce different names, you can put them in different namespaces. e.g.

pub(crate) mod detail {
    struct Ce<'a, T> {
        err: &'a T,
    }
}
pub type Ce<T = String> = detail::Ce<'static, T>;
1 Like

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.