Rust代码编译报错‘lifetime may not live long enough’的原因解析
Rust生命周期错误:
lifetime may not live long enough 原因解析 先看你的代码:
pub struct Writer<'a> { target: &'a mut String, } impl<'a> Writer<'a> { fn indent<'b>(&'b mut self) -> &'a String { self.target } }
编译时触发的错误:
error: lifetime may not live long enough --> src/bin/main29.rs:19:9 | 17 | impl<'a> Writer<'a> { | -- lifetime `'a` defined here 18 | fn indent<'b>(&'b mut self) -> &'a String { | -- lifetime `'b` defined here 19 | self.target | ^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` | = help: consider adding the following bound: `'b: 'a`
核心原因:生命周期约束不匹配
这里的关键是搞懂'a和'b的含义以及它们的关系:
'a是Writer结构体中target引用的生命周期,代表target的存活时长至少和Writer实例一致。'b是indent方法中self可变引用的生命周期,也就是这次方法调用中self被借用的时长。
当你返回&'a String时,本质是把&'a mut String转成了不可变引用,但Rust的借用规则要求:这个不可变引用的存活时间不能超过self可变引用的生命周期'b——因为可变引用具有排他性,只要self还处于可变借用状态(&'b mut self),就不能有任何比'b更长的引用存在,否则会导致悬垂引用或数据竞争风险。
你的代码没有给'b和'a添加约束,编译器默认认为'b可能比'a短。如果'b更短,那返回的&'a String就会在self的可变借用结束后继续存活,这违反了Rust的安全规则,所以编译器报错。
解决办法
按照错误提示添加'b: 'a约束,告诉编译器'b的生命周期至少和'a一样长,这样返回的&'a String就被包含在'b的生命周期内,不会有安全问题:
pub struct Writer<'a> { target: &'a mut String, } impl<'a> Writer<'a> { fn indent<'b: 'a>(&'b mut self) -> &'a String { self.target } }
或者更简洁的写法,让编译器自动推导生命周期(效果完全一致):
pub struct Writer<'a> { target: &'a mut String, } impl<'a> Writer<'a> { fn indent(&mut self) -> &'a String { self.target } }
内容的提问来源于stack exchange,提问作者BaiTang
相关产品推荐
相关产品推荐

