recursion - 递归结构错误生命周期(无法为函数调用中的生命周期参数推断适当的生命周期... [E0495])

标签 recursion struct rust lifetime

<分区>

我无法计算出此代码的生命周期参数。我尝试的所有操作通常都会导致编译器错误:

consider using an explicit lifetime parameter as shown

或者类似的东西

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

Entity , Reference是简化版本,以保持此示例最小化。

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

最佳答案

我看错方向了。因此,我找到了解决方案,但不幸的是它并不安全。

  • 您可以使用 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>,
}

Rust Playground :https://play.rust-lang.org/?gist=8237d8cb80a681c981a85610104f2e5c&version=stable&backtrace=0

关于recursion - 递归结构错误生命周期(无法为函数调用中的生命周期参数推断适当的生命周期... [E0495]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39365302/

相关文章:

algorithm - 递归和动态规划

c++ - 给定结构类型返回某个字符缓冲区的绝对最快(并且希望优雅)的方法

namespaces - 禁用默认命名空间

generics - 如何在堆上构造动态大小的对象

c++ - 递归地将一组 QuadTree 节点折叠到它们的父节点中?

java - 为什么这个例子的时间复杂度是从 "Cracking the Coding Interview"O(k c^k)?

c++ - 如何在方法中使用 vector 和结构成员

c++ - 按值传递类和结构

rust - 尽管值已经存在,Entry::or_insert 仍会执行

python - 拉普拉斯展开复杂度计算(递归)