匹配File :: create的结果

时间:2015-03-25 18:19:16

标签: 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));
}
然后调用

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;
}

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

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`.

std::fs::File::create的签名是fn create<P: AsRef<Path>>(path: P) -> Result<File>,所以我不应期待&#34;展开&#34;使用匹配的值?为什么期望File值?

1 个答案:

答案 0 :(得分:7)

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

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

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

fn main() {}

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

run on the 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))
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

问题是因为您已将函数的返回类型定义为File,但函数体返回Result

fn allocate(path: &str) -> File

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

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

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

use std::io;

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

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

use std::fs::File;

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

fn main() {
    match allocate() {
        Ok(..) => println!("OK!"),
        Err(..) => println!("Bad!"),
    }
}

在这里,我们尝试在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!"),
                 ^~~~~~