1
\$\begingroup\$

I'm basically wondering what the optimal method for returning to the top of src/main.rs::main() is?

Maybe something like this:

mod main;

pub fn main() {
    crate::main();
}

Or maybe there's a keyword built in?

I want to handle certain kinds of errors by 'restarting the program'.

\$\endgroup\$
  • 3
    \$\begingroup\$ generally people use a loop \$\endgroup\$ – Stargateur Feb 2 at 2:00
  • \$\begingroup\$ @Stargateur Yes, I thought people might do something using returns and breaks (so some kind of loop), but I don't know how to reference it (for example should I search for "main loop"? What kind of book would I find this info in (like an algorithms book, or a basic programming patterns book)? I'm trying to break into programming, and I feel like I'm puzzling through every little thing like this after having finished reading the primer and going through its examples: just putting the pieces together is a much bigger challenge. \$\endgroup\$ – Wolfpack'08 Feb 2 at 7:20
2
\$\begingroup\$

There is a lot of way, I advice the simple one, use a loop:

enum Error {
    A,
}

fn run() -> Result<(), Error> {
    if rand::random() {
        Ok(())
    } else {
        Err(Error::A)
    }
}

pub fn main() {
    while let Err(_) = run() {
        println!("Hello");
    }
}

However, be sure the program end maybe add a maximum fail counter.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks. I feel the program can end because: if a module fails in a specific way, I hope it returns to main. Picture a game where if you die at a specific time/place, you go back to the main menu. There are ways to succeed and ways to die that don't cause you to go back to the main menu (like find a save point). \$\endgroup\$ – Wolfpack'08 Feb 3 at 1:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.