왜이 평생 오류가 없습니다 :변경할 수없는 참조 대신 구조체에서 변경 가능한 참조를 사용하면 평생 오류가 발생하는 이유는 무엇입니까?
fn main() {
struct f<'a> {
x: &'a i32,
}
impl<'a, 'b> f<'a> {
fn get(&'b self) -> &'a i32 {
self.x
}
}
let x = 3;
let y = f { x: &x };
let z = f::get(&y);
}
을하지만이
fn main() {
struct f<'a> {
x: &'a mut i32,
}
impl<'a, 'b> f<'a> {
fn get(&'b self) -> &'a i32 {
self.x
}
}
let mut x = 3;
let y = f { x: &mut x };
let z = f::get(&y);
}
이 오류가 있습니다
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/main.rs:7:13
|
7 | self.x
| ^^^^^^
|
note: ...the reference is valid for the lifetime 'a as defined on the block at 6:36...
--> src/main.rs:6:37
|
6 | fn get(&'b self) -> &'a i32 {
| ^
note: ...but the borrowed content is only valid for the lifetime 'b as defined on the block at 6:36
--> src/main.rs:6:37
|
6 | fn get(&'b self) -> &'a i32 {
| ^
help: consider using an explicit lifetime parameter as shown: fn get(&'a self) -> &'a i32
--> src/main.rs:6:9
|
6 | fn get(&'b self) -> &'a i32 {
| ^
정확히 모르겠지만, f의 x를 더 이상 변경할 수 없으므로 두 번째 예제가 실패하는 것이 중요하다고 생각합니다. – torkleyy
주 :'f'는'F'이어야하며,'y.get()'을 직접 호출 할 수 있습니다 ... 나는이 질문을 정말 좋아합니다! –
와우, 시간이 좀 걸렸지 만 나는 마침내 여기에서 무슨 일이 일어나고 있었는지 정확히 이해하고이 토끼 구멍을 내려가는 것이 정말 멋지다고 생각한다. 다시 질문 주셔서 감사합니다! –