2016-09-07 20 views
0

我找不出這個代碼的生命週期參數。一切我通常會嘗試導致編譯器錯誤:遞歸結構錯誤壽命(無法推斷函數調用中的生命週期參數的適當壽命... [E0495])

consider using an explicit lifetime parameter as shown

或類似

in type &'ent Entity<'a, 'ent> , reference has a longer lifetime than the data it references.

EntityReference簡化版本,以保持這個例子微乎其微。

struct Entity<'a> { 
    id: i32, 
    name: &'a str, 
    references: Option<Vec<Reference<'a>>>, 
} 

struct Reference<'a> { 
    entity: &'a Entity<'a>, 
} 

fn main() { 
    let mut ents: Vec<Entity> = vec![Entity { 
             id: 0, 
             name: "Zero", 
             references: None, 
            }, 
            Entity { 
             id: 1, 
             name: "One", 
             references: None, 
            }, 
            Entity { 
             id: 2, 
             name: "Two", 
             references: None, 
            }, 
            Entity { 
             id: 3, 
             name: "Three", 
             references: None, 
            }]; 
    let references_ents_id = vec![vec![3, 1, 2], vec![1], vec![0, 3], vec![3, 0]]; 
    create_references(&references_ents_id, &mut ents); 
} 

fn create_references(refs_id: &Vec<Vec<i32>>, ents_vec: &mut Vec<Entity>) { 
    for (id_ent, references) in refs_id.iter().enumerate() { 
     let mut references_of_ent: Vec<Reference> = vec![]; 
     for id_ent in references { 
      references_of_ent.push(Reference { 
       entity: ents_vec.iter().find(|ent| ent.id == *id_ent).unwrap(), 
      }); 
     } 
     ents_vec[id_ent].references = Some(references_of_ent); 
    } 
} 

Rust Playground

回答

0

我一直在尋找在錯誤的方向。所以,我找到了解決方案,但不幸的是它並不安全。

  • 可以使用RcWeak允許節點共享所有權實現它,雖然這種方法支付內存管理的成本。
  • 您可以使用原始指針使用不安全的代碼來實現它。這將會更有效率,但繞過Rust的安全保證。
  • 使用借閱的參考文獻UnsafeCell

Rust FAQ

Other answer on SO

的執行不安全的版本與原始指針示例:

struct Entity<'a> { 
    id: i32, 
    name: &'a str, 
    references: Option<Vec<Reference<'a>>>, 
} 

struct Reference<'a> { 
    entity: *const Entity<'a>, 
} 

鏽病遊樂場:https://play.rust-lang.org/?gist=8237d8cb80a681c981a85610104f2e5c&version=stable&backtrace=0