相关疑难解决方法(0)

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

我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:

struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)

有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:

struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)

有时,我甚至没有参考该值,我得到同样的错误:

struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)

在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?

lifetime rust borrow-checker

193
推荐指数
3
解决办法
2万
查看次数

如何在安全的Rust中表达相互递归的数据结构?

我正在尝试在Rust中实现类似scenegraph的数据结构.我想在安全 Rust中表示这个C++代码的等价物:

struct Node
{
    Node* parent; // should be mutable, and nullable (no parent)
    std::vector<Node*> child;

    virtual ~Node() 
    { 
        for(auto it = child.begin(); it != child.end(); ++it)
        {
            delete *it;
        }
    }

    void addNode(Node* newNode)
    {
        if (newNode->parent)
        {
            newNode->parent.child.erase(newNode->parent.child.find(newNode));
        }
        newNode->parent = this;
        child.push_back(newNode);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要的属性:

  • 父母拥有其子女的所有权
  • 可以通过某种参考从外部访问节点
  • 触摸一个事件的事件Node可能会改变整个树

rust data-structures

23
推荐指数
3
解决办法
4415
查看次数

如何建模复杂的递归数据结构(图形)?

我对Rust非常感兴趣,现在我开始用语言开展我的第一个非平凡的项目.我仍然在完全理解借贷和终身概念方面遇到一些麻烦.

该应用程序是一个逻辑门模拟器,其中组件是递归定义的(就其他组件及其互连而言).

我目前的计划是通过让Component组件拥有一个Components(它的子组件)向量和一个Nets向量来描述这些组件之间的相互连接,就像在C++中一样实现它:

pub struct Pin {
    name: String
}

pub struct Net<'a> {
    nodes: Vec<(&'a Component<'a>,&'a Pin)>
}

pub struct Component<'a> {
    sub_components: Vec<Box<Component<'a>>>,
    in_pins: Vec<Pin>,
    out_pins: Vec<Pin>,
    netlist: Vec<Net<'a>>
}

impl<'a> Component<'a> {
    pub fn new() -> Component<'a> {
        ...
    }

    pub fn add_subcomponent( & mut self, comp: Component<'a> ) {
        // -> &Box<Component<'a>> ??
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

在C++中,Net很容易实现为指向组件的指针数组,但我不确定在Rust中执行此操作的最佳方法,我想我应该使用借来的指针?或者,还有更好的方法?

请考虑以下主要内容:

fn main() {
    let sub1 = Component::new();
    let sub2 = Component::new();
    let circuit = Component::new();

    circuit.add_subcomponent( sub1 ); …
Run Code Online (Sandbox Code Playgroud)

rust

20
推荐指数
1
解决办法
2664
查看次数

标签 统计

rust ×3

borrow-checker ×1

data-structures ×1

lifetime ×1