2017-01-08 2 views
1

녹 발생 수명 문제가 발생하여 문제가 발생했습니다. 아래에 많은 조정을 시도했지만 새로운 오류를 계속 도입합니다. Vector 객체를 반환하기 위해 인덱스를 원합니다.녹 수명 - 변수가 충분히 오래 살지 못함 오류

struct Matrix<T> { 
    num_rows: i32, 
    num_cols: i32, 
    data: Vec<T> 
} 

struct Vector<T> { 
    data: Vec<T> 
} 

그리고

impl<T: Clone> Index<usize> for Matrix<T> { 
    type Output = Vector<T>; 

    fn index(&self, i: usize) -> &Vector<T> { 
     let index = i as i32; 
     let start = (index * &self.num_cols) as usize; 
     let end = (((index + 1) * &self.num_cols) - 1) as usize; 
     let data_slice = &self.data[start..end]; 
     let data = data_slice.to_vec(); 
     let vector_temp = Vector::<T>::new(data); 
     return &vector_temp; 
    } 
} 

을 할 노력하고있어하지만 난 아직 완전히 녹 수명을 grokked하지 않은

error: `vector_temp` does not live long enough 
    --> src\main.rs:45:17 
    | 
45 |   return &vector_temp; 
    |     ^^^^^^^^^^^ does not live long enough 
46 |  } 
    |  - borrowed value only lives until here 
    | 
note: borrowed value must be valid for the anonymous lifetime #1 defined on  the block at 38:44... 
    --> src\main.rs:38:45 
    | 
38 |  fn index(&self, i: usize) -> &Vector<T> { 
    |           ^

error: aborting due to previous error 

error: Could not compile `hello_world`. 

받고 있어요 :

나는이 누군가가 나를 도울 수 있기를 바랬습니다. 감사!

답변

3

일단 함수가 끝나면 파괴 될 개체에 대한 참조를 반환하려고합니다. vector_temp은 더 이상 존재하지 않으며 index이 반환되므로 해당 참조는 아무 것도 가리 키지 않으므로 불법입니다.

impl<T: Clone> Index<usize> for Matrix<T> { 
    type Output = [T]; 

    fn index(&self, i: usize) -> &[T] { 
     let index = i as i32; 
     let start = (index * &self.num_cols) as usize; 
     let end = (((index + 1) * &self.num_cols) - 1) as usize; 

     &self.data[start..end] 
    } 
} 

그런 다음 발신자가 원래의 구현에 한 일을 할 수 있습니다 : 당신이 원하는 무엇

, 당신이 만드는 슬라이스를 반환하고 발신자가 수행 할 작업을 결정하게하다 :

let m1 = Matrix { ... }; 
let owned_vector = m1[index_here].to_owned(); 

I am not 100% sure where you go from here, 난 당신이 걸릴 것 얼마나 많은 더 모르겠어요 주어진. 크기가 지정되지 않은 슬라이스를 반환하면 문제가 발생할 수 있으므로 특정 사용 사례를 알지 못하면이 문제를 해결할 수있는 더 좋은 방법이 있는지 확실하지 않습니다.

이 정보가 귀하의 즉각적인 문제 해결에 도움이되기를 바랍니다.

관련 문제