相关疑难解决方法(0)

有没有办法返回对函数中创建的变量的引用?

我想编写一个程序,分两步编写一个文件.在程序运行之前,该文件可能不存在.文件名是固定的.

问题是OpenOptions.new().write()可能会失败.在这种情况下,我想调用自定义函数trycreate().我们的想法是创建文件而不是打开它并返回一个句柄.由于文件名是固定的,trycreate()没有参数,我不能设置返回值的生命周期.

我该如何解决这个问题?

use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;

fn trycreate() -> &OpenOptions {
    let f = OpenOptions::new().write(true).open("foo.txt");
    let mut f = match f {
        Ok(file)  => file,
        Err(_)  => panic!("ERR"),
    };
    f
}

fn main() {
    {
        let f = OpenOptions::new().write(true).open(b"foo.txt");
        let mut f = match f {
            Ok(file)  => file,
            Err(_)  => trycreate("foo.txt"),
        };
        let buf = b"test1\n";
        let _ret = f.write(buf).unwrap();
    }
    println!("50%");
    {
        let f = OpenOptions::new().append(true).open("foo.txt");
        let mut f …
Run Code Online (Sandbox Code Playgroud)

reference lifetime rust

31
推荐指数
4
解决办法
1万
查看次数

如何在安全的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
查看次数

如何在不破坏封装的情况下返回对RefCell内部内容的引用?

我有一个内部可变性的结构.

use std::cell::RefCell;

struct MutableInterior {
    hide_me: i32,
    vec: Vec<i32>,
}
struct Foo {
    //although not used in this particular snippet,
    //the motivating problem uses interior mutability
    //via RefCell.
    interior: RefCell<MutableInterior>,
}

impl Foo {
    pub fn get_items(&self) -> &Vec<i32> {
        &self.interior.borrow().vec
    }
}

fn main() {
    let f = Foo {
        interior: RefCell::new(MutableInterior {
            vec: Vec::new(),
            hide_me: 2,
        }),
    };
    let borrowed_f = &f;
    let items = borrowed_f.get_items();
}
Run Code Online (Sandbox Code Playgroud)

产生错误:

error[E0597]: borrowed value does not live long enough
  --> …
Run Code Online (Sandbox Code Playgroud)

encapsulation contravariance mutability rust interior-mutability

21
推荐指数
3
解决办法
2487
查看次数

如何借用Option <T>中的内容?

如何Option从调用者的特定生命周期中提取引用并将其传回?

具体而言,我想借用参照Box<Foo>Bar一个具有Option<Box<Foo>>在其中.我以为我能做到:

impl Bar {
    fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
        match self.data {
            Some(e) => Ok(&e),
            None => Err(BarErr::Nope),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

......但结果是:

error: `e` does not live long enough
  --> src/main.rs:17:28
   |
17 |             Some(e) => Ok(&e),
   |                            ^ does not live long enough
18 |             None => Err(BarErr::Nope),
19 |         }
   |         - borrowed value only lives until here
   |
note: borrowed value must be valid for the …
Run Code Online (Sandbox Code Playgroud)

rust

20
推荐指数
2
解决办法
8193
查看次数