How do I exit a Rust program early from outside the main function?

前端 未结 2 1072
故里飘歌
故里飘歌 2020-12-30 19:11

I am in the process of writing a bash clone in Rust. I need to have my program exit when the user types exit. In previous iterations of my progra

2条回答
  •  醉酒成梦
    2020-12-30 19:46

    panic!("Oh no something bad has happened!")
    

    Example:

        if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); }
    

    In older documentation, you will see this as fail!("Oh no something bad here has happened.")

    For some reason, this macro was changed from fail to panic. Panic is the way to fail, if you must.

    [edit] I am sorry. It looks like you should be testing input for the string "exit," which would depend on how you are taking input (by line or by args). Then you can have the program break out of the loop on the condition that the exit is detected.

    Example:

    loop {
        if exit_found { break }
        else {
            // your thing, which also looks for exit_found
        }
    }
    

提交回复
热议问题