struct SystemTime中不存在字段tv_sec

问题描述 投票:0回答:1

我正在尝试最后一次修改文件,但是我收到了一个找不到字段的错误。

use std::{fs, io, time};

fn main() -> io::Result<()> {
    let metadata = fs::metadata("foo.txt")?;
    let _time: time::SystemTime = metadata.modified().unwrap();
    let last_modified = _time.tv_sec;

    println!("{:?}", last_modified);
    Ok(())
}
error[E0609]: no field `tv_sec` on type `std::time::SystemTime`
 --> src/main.rs:6:31
  |
6 |     let last_modified = _time.tv_sec;
  |                               ^^^^^^ unknown field

我也试过使用结果而不解包,但后来我想到访问结构的tv_sec字段的同一点。

作为展开之前的参考,结果是Ok(SystemTime { tv_sec: 000, tv_nsec: 000 }),在解开后它只是SystemTime { tv_sec: 000, tv_nsec: 000 })

我是Rust的新手,但我已经梳理了文档,而且从文档来看,我应该能够访问SystemTime结构的字段。

rust
1个回答
5
投票

您无法访问tv_sec,因为该字段不公开。这称为可见性,您可以在chapter 7.2 of the book中阅读它。

你只能在SystemTime上找到可以在API of SystemTime找到的公共方法。


出现“奇怪”错误消息的原因是,虽然调试表示它是一个“扁平”结构(例如它有两个字段tv_sectv_nsec),it is actually a tuple struct,这意味着你必须调用.0来获得内部字段然后会导致错误

error[E0616]: field `0` of struct `std::time::SystemTime` is private
  --> src/main.rs:10:22
   |
10 |     println!("{:?}", time.0);
   |                      ^^^^^^

这样做是为了抽象不同的操作系统;例如,Windows处理时间的方式与Unix不同。


如果你想在几秒钟内得到“年龄”你可以通过使用Duration将它转换为SystemTime::elapsed,它将返回Duration,你可以通过使用Duration::as_secs得到秒。

© www.soinside.com 2019 - 2024. All rights reserved.