我正在运行:
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,并且不知道我做错了什么。
答案 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>