Struct With Two Independent Lifetimes

Give each borrowed field its own lifetime parameter so one source may end while the other still lives, instead of forcing both to share 'a.

RustData Integrity

Code

rustsnippet
37 lines
// 两个字段各自持有独立生命周期:'h 只约束 header,'v 只约束 values
struct Row<'h, 'v> {
    header: &'h [String],
    values: &'v [String],
}

impl<'h, 'v> Row<'h, 'v> {
    fn column(&self, name: &str) -> Option<&str> {
        self.header
            .iter()
            .position(|h| h == name)
            .and_then(|i| self.values.get(i).map(|v| v.as_str()))
    }
}

fn pair<'h, 'v>(header: &'h [String], values: &'v [String]) -> Row<'h, 'v> {
    Row { header, values }
}

fn main() {
    let header = vec!["id".to_string(), "name".to_string()];
    let first_col: &str;
    {
        // 行数据来源不同、生命周期更短
        let values = vec!["7".to_string(), "ada".to_string()];
        let row = pair(header.as_slice(), values.as_slice());
        println!("name column: {:?}", row.column("name"));

        // 只把 'h 这一半的借用带出内层作用域:first_col 指向 header,
        // 'v 已随 values 结束,与这个外层借用无关
        first_col = row.header[0].as_str();
    }
    // 若两个字段共用一个 'a,values 的借用也被迫活到这一行,
    // 而 values 已析构——编译失败
    println!("header survives: {}", first_col);
    println!("{:?}", header);
}

Why two lifetime parameters unlock this shape

struct Row<'h, 'v> gives each borrowed field its own lifetime: 'h constrains only header, 'v only values. In main, header lives for the whole function while values is created inside an inner block — so the Row built by pair holds one long borrow and one short one. When the inner block ends, the 'v borrow dies with values, but first_col = row.header[0].as_str() carries only the 'h half out to the later println!("header survives: {}", first_col). Had both fields shared a single 'a, the compiler would force the values borrow to live as long as first_col — past values’ destructor — and the file would not compile, which is exactly what the last comment says.

What the demo prints

name column: Some("ada")
header survives: id
["id", "name"]

Line one comes from row.column("name"): self.header.iter().position(|h| h == name) lands on index 1, and self.values.get(1) yields "ada" from the short-lived values — a lookup that works only because the method borrows both fields through the same struct instance. The remaining lines show the 'h borrow surviving the inner scope (first_col reads "id" from header) and the owned header vec still intact.

The line that carries one borrow out of the block

first_col = row.header[0].as_str();

This assignment is where the two lifetimes diverge: the field access names header specifically, so only 'h is extended, and the borrow checker lets the code past the closing brace.

Interactive Tools for This Topic

FAQ

What does Struct With Two Independent Lifetimes print when run?
The script runs standalone; its 2 labeled outputs include `name column:`, `header survives:`.