我想编写一个程序,分两步编写一个文件.在程序运行之前,该文件可能不存在.文件名是固定的.
问题是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) 如何正确创建成员Vec?我在这里想念什么?
struct PG {
names: &mut Vec<String>,
}
impl PG {
fn new() -> PG {
PG { names: Vec::new() }
}
fn push(&self, s: String) {
self.names.push(s);
}
}
fn main() {
let pg = PG::new();
pg.push("John".to_string());
}
Run Code Online (Sandbox Code Playgroud)
如果我编译此代码,则会得到:
struct PG {
names: &mut Vec<String>,
}
impl PG {
fn new() -> PG {
PG { names: Vec::new() }
}
fn push(&self, s: String) {
self.names.push(s);
}
}
fn main() {
let pg = PG::new();
pg.push("John".to_string());
} …Run Code Online (Sandbox Code Playgroud)