rust - 如何访问 SystemTime 中的 as_secs?为枚举结果找到 "no method named ` as_secs”

标签 rust systemtime

我正在使用 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, _)返回一个 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. */
}

关于rust - 如何访问 SystemTime 中的 as_secs?为枚举结果找到 "no method named ` as_secs”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58124073/

相关文章:

rust - 如何使 Rust 函数 `zip_map` 采用二元函数而不是以二元组作为参数的一元函数?

generics - 是否可以对 HashMap 的键和值使用单个泛型?

rust - 实现 Deref 特征时无法为生命周期参数推断出合适的生命周期

c++ - 如何在没有 root 权限的情况下更改 Linux 系统时间?

rust - 正在释放的Rust指针未分配错误

rust - 为什么 mem::forget & ManuallyDrop 似乎对 String -> &'static str 转换的 Box::leak 没有影响?

java - 如何在java中获取系统日期和时间格式?

c++ - 使用 SYSTEMTIME、FILETIME 和 ULARGE_INTEGER 修改日期和时间值

java - 如何通过系统时钟篡改来防止使用过期的许可证?

android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24) 返回 null