lifetime

Rust Variance of composite types

A composite type derives its variance from the positions in which its parameters occur. A wrapper containing only a shared borrowed label allows shortening that label lifetime. Adding a writable or differently variant field may restrict conversions. Expected output (not executed): Sale Why: The shared reference field makes Label covariant over its lifetime. Common mistake: Assuming every struct with a lifetime parameter is covariant regardless of its fields.

Formal Syntax & Structure

rust syntaxrust
struct Label<'a>(&'a str);

Working Example

Example Snippetrust
struct Label<'a>(&'a str);fn localize<'a>(_: &'a str, label: Label<'static>) -> Label<'a> { label }fn main() {    let session = String::from("cart");    let tag = localize(&session, Label("Sale"));    println!("{}", tag.0);}
Rust Reference