匹配 File::create 的结果

Matching on the result of File::create

我正在尝试编写一个必须打开文件的库,并且我想处理 std::fs::File::create 使用的 Result 类型。鉴于此包装函数,我不知道如何匹配 return 结果:

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> 所以我不应该期望 "unwrap" 使用匹配的值吗?为什么需要 File 值?

让我们看一下代码的简化版本,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))
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

fn allocate(path: &str) -> File

您需要确保函数的类型与函数的作用一致。最简单的是 unwrap 结果,这会导致失败情况下的线程恐慌。

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

你也可以 return 你自己的 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!"),
    }
}

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