匹配File :: create的结果

xrl*_*xrl 1 error-handling rust

我正在尝试编写一个必须打开文件的库,我想处理使用的Result类型std::fs::File::create.鉴于此包装函数,我无法弄清楚如何匹配返回结果:

use std::fs::File;
use std::path::Path;
use std::fs::File;
use std::path::Path;

pub fn allocate(path:& str) -> File{
  let mut file = File::create(Path::new(path));
}
Run Code Online (Sandbox Code Playgroud)

然后调用:

mod whisper;
use std::io::Write;

fn main(){
  let mut handle = whisper::allocate("./a_file.wsp");

  match handle {
    Ok(_) => println!("success!"),
    Err(e) => println!("sorry, got {}",e),
  }

  return;
}
Run Code Online (Sandbox Code Playgroud)

但由于类型不匹配,代码无法编译:

Xaviers-MacBook-Pro:graphite-rust xavierlange$ cargo build
   Compiling graphite-rust v0.0.1 (file:///Users/xavierlange/code/viasat/graphite-rust)
src/main.rs:8:5: 8:10 error: mismatched types:
 expected `std::fs::File`,
    found `core::result::Result<_, _>`
(expected struct `std::fs::File`,
    found enum `core::result::Result`) [E0308]
src/main.rs:8     Ok(_) => println!("hi!"),
                  ^~~~~
src/main.rs:9:5: 9:11 error: mismatched types:
 expected `std::fs::File`,
    found `core::result::Result<_, _>`
(expected struct `std::fs::File`,
    found enum `core::result::Result`) [E0308]
src/main.rs:9     Err(e) => println!("sorry, got {}",e),
                  ^~~~~~
error: aborting due to 2 previous errors
Could not compile `graphite-rust`.
Run Code Online (Sandbox Code Playgroud)

签名std::fs::File::createfn create<P: AsRef<Path>>(path: P) -> Result<File>不是我不应该期望使用匹配"解包"该值?为什么期待File价值?

She*_*ter 7

让我们看一下代码的简化版本MCVE.在编程时创建小例子非常有用,因为它可以帮助您一次专注于一个问题:

use std::fs::File;
use std::path::Path;

fn allocate(path: &str) -> File {
    File::create(Path::new(path))
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

(我也冒昧地将你的代码与普遍的Rust风格对齐;我强烈建议你学习它并喜欢它以便更好地进行社区互动!)

在Playpen上运行时会出现相同的错误:

<anon>:5:5: 5:34 error: mismatched types:
 expected `std::fs::File`,
    found `core::result::Result<std::fs::File, std::io::error::Error>`
(expected struct `std::fs::File`,
    found enum `core::result::Result`) [E0308]
<anon>:5     File::create(Path::new(path))
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

问题是因为你已经将函数的返回类型定义为a File,但是函数的主体正在返回一个Result!

fn allocate(path: &str) -> File
Run Code Online (Sandbox Code Playgroud)

您需要确保函数上的类型以及函数的对齐方式.最简单的是unwrap结果,这会导致线程在故障情况下出现恐慌.

fn allocate(path: &str) -> File {
    File::create(Path::new(path)).unwrap()
}
Run Code Online (Sandbox Code Playgroud)

您也可以返回Result自己的,然后强制调用者处理失败(我的首选):

use std::io;

fn allocate(path: &str) -> io::Result<File> {
    File::create(Path::new(path))
}
Run Code Online (Sandbox Code Playgroud)

查看错误的另一种方法是这一半:

use std::fs::File;

fn allocate() -> File { unimplemented!() }

fn main() {
    match allocate() {
        Ok(..) => println!("OK!"),
        Err(..) => println!("Bad!"),
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们试图matchFile,但File不与变种枚举OkErr-这将是Result!因此,您会收到一个错误,指出:

<anon>:7:9: 7:15 error: mismatched types:
 expected `std::fs::File`,
    found `core::result::Result<_, _>`
(expected struct `std::fs::File`,
    found enum `core::result::Result`) [E0308]
<anon>:7         Ok(..) => println!("OK!"),
                 ^~~~~~
Run Code Online (Sandbox Code Playgroud)