lifetime
Rust Store borrowed data in an enum
An enum can carry a borrowed value in a variant. A lifetime parameter makes the borrowing relationship part of the enum type even when another variant has no reference. Match the variant to access the borrowed content. Expected output (not executed): pending packed Why: The Ready variant carries a shared string view; Pending carries no data. Common mistake: Assuming switching to an enum removes the lifetime constraint on a borrowed field.
Formal Syntax & Structure
rust syntaxrust
enum Message<'a> { Text(&'a str), Empty }Working Example
Example Snippetrust
enum Status<'a> { Pending, Ready(&'a str) }fn show(status: Status<'_>) { match status { Status::Pending => println!("pending"), Status::Ready(text) => println!("{text}"), }}fn main() { let text = String::from("packed"); show(Status::Pending); show(Status::Ready(&text));}