英文:
Rust Type mismatch when pattern matching on File::create()
问题
我试图进行模式匹配,当文件不存在时,将创建并返回文件,但编译器期望'()',我不确定如何使其期望正确的返回类型File。
```rust
let mut file = match File::open(&path) {
Err(_) => match File::create(&path) {
Err(e) => panic!("读取或创建文件时出现问题: {}", e),
Ok(mut file) => {
let msg: &str = "项目路径:\n";
let f = match file.write_all(msg.as_bytes()) {
Err(e) => panic!("初始化问题: {}", e),
Ok(_) => file,
};
return f;
}
}
Ok(file) => file,
};
我能够使其创建文件,如果文件不存在,但尝试写入并返回文件似乎有些棘手,因为Err(_)
期望()
作为返回类型
let mut file = match File::open(path) {
Err(_) => match File::create(path) {
Err(e) => panic!("读取或创建文件时出现问题: {}", e),
Ok(_) => File::open(path)
.unwrap_or_else(|e| panic!("读取文件问题: {}", e)),
},
Ok(file) => file,
};
英文:
I'm trying to pattern match when a file doesn't exist, wherein it would be created and then returned but the compiler is expecting '()', I'm not sure how to get it to expect the correct return type of File.
let mut file = match File::open(&path) {
Err(_) => match File::create(&path) {
Err(e) => panic!("issue reading or creating file: {}", e),
Ok(mut file) => {
let msg: &str = "Project Paths:\n";
let f = match file.write_all(msg.as_bytes()) {
Err(e) => panic!("issue initializing: {}", e),
Ok(_) => file,
};
return f;
}
}
Ok(file) => file,
};
i was able to get it to create the file if it doesn't exist but trying to get it to write and then return the file seems to be tricky as the Err(_)
expects ()
as a return type
let mut file = match File::open(path) {
Err(_) => match File::create(path) {
Err(e) => panic!("issue reading or creating file: {}", e),
Ok(_) => File::open(path)
.unwrap_or_else(|e| panic!("reading file issue{}", e)),
},
Ok(file) => file,
};
答案1
得分: 2
以下是代码部分的翻译:
let mut file = File::open(path)
.or_else(|_| File.create(path))
.expect(format!("issue reading or creating file: {}", e));
let mut file = File::open(path).or_else(|_| File.create(path))?;
请注意,以上翻译是代码的翻译部分,不包括问题部分。
英文:
A more compact version might look like:
let mut file = File::open(path)
.or_else(|_| File.create(path))
.expect(format!("issue reading or creating file: {}", e));
Where you can get most of that done in one shot. You can always switch to a more panic!
driven style, but in practice you'll want to steer towards propagation via Result
using ?
, like:
let mut file = File::open(path).or_else(|_| File.create(path))?;
Where that function just propagates the error up the chain to something else that handles it, panic!
or otherwise.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论