我在用std::time::SystemTime。我的目标是用一个名为timestamp的字段创建一个结构,并以秒为单位存储时间。
我看到了这个正确工作的例子:
use std::time::SystemTime;
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}当我尝试这段代码时,我会得到一个错误:
use std::time::SystemTime;
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
println!("{}", n.as_secs());error[E0599]: no method named `as_secs` found for enum `std::result::Result<std::time::Duration, std::time::SystemTimeError>` in the current scope
--> src/main.rs:5:22
|
5 | println!("{}", n.as_secs());
| ^^^^^^^ method not found in `std::result::Result<std::time::Duration, std::time::SystemTimeError>`我做错了什么?
发布于 2019-09-27 02:38:23
阅读错误:
no method named `...` found for type `Result<...>`所以,我们来看看Result
Result是一种表示成功(Ok)或错误(Err)的类型,请参阅std::result模块获取文档详细信息。
因此,我们知道SystemTime::duration_since(&self, _)返回一个Result,这意味着它可能失败了。阅读文档:
返回一个
Err,如果earlier比self晚,并且错误包含离self时间有多远。
因此,我们只需对其进行unwrap、expect或匹配,就可以获得错误的可能性:
use std::time::SystemTime;
// Unwrapping
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.unwrap(); // Will panic if it is not `Ok`.
// Expecting
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.expect("Invalid time comparison"); // Will panic with error message
// if it is not `Ok`.
// Matching
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
match n {
Ok(x) => { /* Use x */ },
Err(e) => { /* Process Error e */ },
}
// Fallibly Destructuring:
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
if let Ok(x) = n {
/* Use x */
} else {
/* There was an error. */
}https://stackoverflow.com/questions/58124073
复制相似问题