相关疑难解决方法(0)

替换可变引用中的字符串是否会泄漏内存?

我偶然发现了以下场景:

fn compute_values(value: &mut String) {
    // the first computation should always work:
    let computed_value = String::from("computed value");
    // override the default String with the computed value:
    *value = computed_value;
    // some more code that returns a Result with values or an error message
}

fn main() {
    let mut value = String::from("default value");
    compute_values(&mut value);
    println!("value: {value}")
}
Run Code Online (Sandbox Code Playgroud)

这段代码按照我的预期使用 my 进行编译rustc 1.74.1 (a28077b28 2023-12-04)并输出value: computed value,但问题是,该代码是否泄漏内存。

据我了解,*value = computed_value;进入并且它不再可用(rust编译器确认了这一点,我之后不能computed_value。)并且在函数作用域结束时不会取消分配。由于这一行有效地将 a 分配给 …

rust

5
推荐指数
1
解决办法
155
查看次数

在构造一棵大树时,"thread'<main>'溢出了它的堆栈"

我实现了一个树结构:

use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use std::cell::RefCell;

struct A {
    children: Option<VecDeque<Rc<RefCell<A>>>>
}

// I got thread '<main>' has overflowed its stack
fn main(){
    let mut tree_stack: VecDeque<Rc<RefCell<A>>> = VecDeque::new();

    // when num is 1000, everything works
    for i in 0..100000 {
        tree_stack.push_back(Rc::new(RefCell::new(A {children: None})));
    }

    println!("{:?}", "reach here means we are not out of mem");
    loop {
        if tree_stack.len() == 1 {break;}

        let mut new_tree_node = Rc::new(RefCell::new(A {children: None}));
        let mut tree_node_children: VecDeque<Rc<RefCell<A>>> = VecDeque::new();

        // combine last …
Run Code Online (Sandbox Code Playgroud)

rust

3
推荐指数
1
解决办法
931
查看次数

如何在方法中将结构的数据分配给self?

我正在尝试修改self临时存储到另一个变量中的内容。在最后一步,我想将变量中的所有数据复制到self.

struct A {
    x: i32,
}

impl A {
    fn new() -> Self {
        Self { x: 0 }
    }

    fn change(&mut self) {
        let mut a = Self::new();
        a.x += 1;

        self = a; // How to copy data from a variable into self?
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

struct A {
    x: i32,
}

impl A {
    fn new() -> Self {
        Self { x: 0 }
    }

    fn change(&mut self) {
        let mut a …
Run Code Online (Sandbox Code Playgroud)

methods reference rust

0
推荐指数
1
解决办法
253
查看次数

如何在可变引用中获取、转换和替换向量?

我有一个struct Database { events: Vec<Event> }。我想应用一些地图和过滤器events。有什么好的方法可以做到这一点?

这是我尝试过的:

fn update(db: &mut Database) {
    db.events = db.events.into_iter().filter(|e| !e.cancelled).collect();
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

cannot move out of `db.events` which is behind a mutable reference
...
move occurs because `db.events` has type `Vec<Event>`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

有什么方法可以说服 Rust 编译器我只是暂时获取字段值吗?

rust

0
推荐指数
1
解决办法
859
查看次数

标签 统计

rust ×4

methods ×1

reference ×1