简体   繁体   中英

How to re-execute a Rust main function?

I am looking to attempt to re-run my application from inside of the application itself.

When the program initially runs, it will try for a file. If the file does not exist, it executes a login module and create the file; if it does exist, it will go straight to the main application module.

This try function is inside of the initial fn main () function.

How would I re-execute the application's main function to re-evaluate whether the file exists?

(Does something like self::main() exist?)

Thanks!!

main is just a function. Call it like any other function:

use std::sync::atomic::{AtomicUsize, Ordering};

static NUMBER_OF_RUNS: AtomicUsize = AtomicUsize::new(3);

fn main() {
    if 0 == NUMBER_OF_RUNS.fetch_sub(1, Ordering::SeqCst) {
        eprintln!("Ending");
    } else {
        eprintln!("Not done yet");
        main();
    }
}
Not done yet
Not done yet
Not done yet
Ending

Now, I would suggest that you not do this . It's basically just weird . Instead, use a loop. I don't even see where you need a loop, all you need is basic conditional logic:

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

fn main() {
    let file = File::open("my_file")
        .or_else(|_| login())
        .expect("Unable to open file");

    println!("main logic");
}

fn login() -> io::Result<File> {
    File::create("my_file")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM