当文件不存在时,File :: open()会发生混乱

时间:2015-10-14 19:23:10

标签: file rust

我正在运行:

function getAge(dateString) {
    var today = new Date();
    var birth = new Date(dateString);
    var timeDiff = today.getTime() - birth.getTime();
    var yearDiff = timeDiff / (24 * 60 * 60 * 1000) / 365.25;
    return yearDiff * 12;
}

收到此错误:

use std::error::Error;
use std::fs::File;

fn main() {
    try_main().unwrap();
}

fn try_main() -> Result<(), Box<Error>> {
    try!(check_file("andre"));
    Ok(())
}

fn check_file(user: &str) -> Result<(), Box<Error>> {
    let suspend_file_name = format!("{}{}", "/var/cpanel/suspended/", user);
    let suspend_file = try!(File::open(suspend_file_name));

    Ok(())
}

我认为这应该会返回错误?我正在使用Rust 1.3,并且不知道我做错了什么。

1 个答案:

答案 0 :(得分:5)

你的程序完全按照你所说的去做。检查此版本:

use std::{error::Error, fs::File, path::PathBuf};

fn main() -> Result<(), Box<Error>> {
    let x = check_file("andre");
    println!("{}", x.is_ok());
    Ok(())
}

fn check_file(user: &str) -> Result<(), Box<Error>> {
    let mut suspend_file_name = PathBuf::from("/var/cpanel/suspended/");
    suspend_file_name.push(user);
    let _suspend_file = File::open(suspend_file_name)?;

    Ok(())
}

输出结果为false,表示check_file的结果为Err。如果您unwrap

  

如果值为Err,则会发生恐慌,并且Err的值会提供紧急消息。

File::open并不会引起恐慌,但明确表示会对Err值发生恐慌方法确实对Err值感到恐慌。< / p>