我想编写一个程序,分两步编写一个文件.在程序运行之前,该文件可能不存在.文件名是固定的.
问题是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) 我正在尝试在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可能会改变整个树我有一个内部可变性的结构.
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
如何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)