rust - 如何返回指向拥有值 "does not live long enough"的指针?

标签 rust borrow-checker

我有以下代码:

struct Node {
    id: uint
}

struct Graph {
    nodes: Vec<Node>
}

impl Graph {

    fn new() -> Graph {
        return Graph { nodes: Vec::new() };
    }

    fn create_node(&mut self) -> &Node {
        let index = self.nodes.len();
        let node = Node { id: index };
        self.nodes.push(node);
        // return &node;           // error: `node` does not live long enough
        return &self.nodes[index]; // ...but this work fine
    }

}

这个想法是该图创建一个新节点并将其“借给”调用该方法的人。但我不知道如何返回对新创建结构的引用。第二次返回工作正常,但显然无效。

如何在不从向量中取回节点的情况下返回节点?

最佳答案

这就是你不能返回 &node 的原因:

fn create_node(&mut self) -> &Node {
    let index = self.nodes.len();
    let node = Node { id: index };
    println!("{}", &node as *const Node);
    self.nodes.push(node);
    println!("{}", &self.nodes[index] as *const Node);
    return &self.nodes[index];
}

这是一个示例输出:

0x7fffc36a3418
0x7f4c96c2d000

如您所见,&node&self.nodes[index] 返回完全不同的值。而且&node(0x7fffc36a3418)在create_node一返回就失效了,因为这个地址指向了create_node调用帧,一个调用帧是当函数返回时释放。

关于rust - 如何返回指向拥有值 "does not live long enough"的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27841657/

相关文章:

rust - 在实现图时,不能借为可变的,因为它已经被借用了

enums - 如何告诉编译器我返回的枚举的变体总是没有生命周期?

rust - Rust,如何从<Option> Some()中 'pull'数据独立使用

rust - 为什么需要导入特征以使用它为类型定义的方法?

loops - 在 Rust 中是否有与 JavaScript 的 forEach 等效的东西?

java - Rust 中的消息摘要

rust - 当使用优化时,rustc 是否总是忽略内联(从不)?

rust - 解决嵌套可变借用冲突的惯用方法

rust - 如何告诉 Rust 编译器借用已经结束?

rust - 为什么不能在同一结构中存储值和对该值的引用?