how to call function in the main process and print value?

Viewed 35

https://doc.rust-lang.org/std/fs/struct.Metadata.html#method.created how to get created time and print it in the main process instead of in the get_created function ?

fn get_created(path: &str) -> std::io::Result<()> {
    let metadata = fs::metadata(path)?;

    if let Ok(time) = metadata.created() {
        println!("{time:?}");
    } else {
        println!("Not supported on this platform or filesystem");
    }
    Ok(())
}

fn main() {
   ??? get_created ???
}
2 Answers
use std::fs;

fn get_created(path: &str) -> std::io::Result<std::time::SystemTime> {
    let metadata = fs::metadata(path)?;

    metadata.created()
}

fn main() {
    match get_created("src/main.rs") {
        Ok(time) => println!("{time:?}"),
        Err(_) => println!("Not supported on this platform or filesystem"),
    }
}

If you want to format the SystemTime, see https://stackoverflow.com/a/45388083/16662168

Don't use ? and put the code in main with error handling?

use std::fs;

fn main() {
    if let Ok(metadata) = fs::metadata(".bashrc") {
        if let Ok(time) = metadata.created() {
            println!("{time:?}");
        } else {
            eprintln!("Not supported on this platform or filesystem");
        }
    } else {
        eprintln!("File not found or something");
    }
}

Or have main return a Result:

use std::fs;

fn main() -> std::io::Result<()> {
    let metadata = fs::metadata(".xxx")?;
    let time = metadata.created()?;
    println!("{time:?}");
    Ok(())
}
Related