如何在 SystemTime 中访问 as_secs? "no method named `as_secs` found for enum Result"

How to access as_secs in SystemTime? "no method named `as_secs` found for enum Result"

我正在使用 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>`

我做错了什么?

读取错误:

no method named `...` found for type `Result<...>`

所以,我们看Result:

Result is a type that represents either success (Ok) or faliure (Err)

See the std::result module for documentation details.

所以,我们知道 SystemTime::duration_since(&self, _) returns a Result,这意味着它可能已经失败了。阅读文档:

Returns an Err if earlier is later than self, and the error contains how far from self the time is.

所以,我们只需要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. */
}