2017-02-22 1 views
2

새 요소를 인스턴스화하고 연결된 목록에 추가 한 다음 방금 만든 요소에 대한 참조를 반환하는 함수를 구현하고 싶습니다.Linkedlist 요소에 대한 참조 반환

use std::collections::LinkedList; 

struct Bar { 
    ll: LinkedList<Foo> 
} 

struct Foo {} 


impl Bar { 
    fn foo_alloc<'a>(&'a mut self) -> &Option<&'a mut Foo> { 
     let foo = Foo{}; 
     self.ll.push_back(foo); 
     &self.ll.front_mut() 
    } 
} 

은 내가 (&'a mut self 통해) Bar 인스턴스에 반환 된 참조의 수명을 바인딩 할 때 다음이 충분해야한다고 생각하지만, 분명히이되지 않습니다 : 이것은 내가 생각 해낸 것입니다.

여기서 오류 발생 :

error: borrowed value does not live long enough 
    --> src/main.rs:14:10 
    | 
14 |   &self.ll.front_mut() 
    |   ^^^^^^^^^^^^^^^^^^^ does not live long enough 
15 |  } 
    |  - temporary value only lives until here 
    | 
note: borrowed value must be valid for the lifetime 'a as defined on the body at 11:59... 
    --> src/main.rs:11:60 
    | 
11 |  fn foo_alloc<'a>(&'a mut self) -> &Option<&'a mut Foo> { 
    | ____________________________________________________________^ starting here... 
12 | |   let foo = Foo{}; 
13 | |   self.ll.push_back(foo); 
14 | |   &self.ll.front_mut() 
15 | |  } 
    | |_____^ ...ending here 

답변

4

문제는 Option 내부 기준을받지 못하면 Option 객체 자체이다. 참조가 아닌 값으로 반환하십시오.

impl Bar { 
    fn foo_alloc(&mut self) -> Option<&mut Foo> { 
     let foo = Foo{}; 
     self.ll.push_back(foo); 
     self.ll.front_mut() 
    } 
} 

기본 평생 공제가 올바른 일을하기 때문에 평생 주석을 삭제했습니다.

+0

예, 해결되었습니다. 'self.ll.front_mut()'은 스택에'Option'을 만들고'&'는 Option에 대한 참조를 반환하려고 시도하기 전에 Option의 레퍼런스를 반환하려고합니다. 방법의 끝? – hansaplast

+0

예, 반환 된 옵션은 임시이므로 참조를 반환 할 수 없습니다. –