Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to break out of a loop and return a value in rust?

I’m doing a match statement like this:

let command: u32 = match command.trim().parse() {
    Ok(num) => {
        num
    },
    Err(_) => {}
}

But this whole thing is in a loop {}

How do I break out of the loop and also return the num?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve been trying something like this:

let command: u32 = match command.trim().parse() {
    Ok(num) => {
        num;
        break 'inner;
    }
}

But that doesn’t return anything because of the semicolon. And if I switch the break and num, the num is unreachable. So how do I combine these two?

This is the whole code:

for n in players {
    println!("It's {}s turn", n.name);

    'inner: loop {
        println!("Input 1 to throw the dice");

        let mut command = String::new();

        io::stdin()
            .read_line(&mut command)
            .expect("Failed to read line");

        let command: u32 = match command.trim().parse() {
            Ok(num) => {
                num;
                break 'inner;
            }
            Err(_) => {
                println!("You need to input 1 to throw");
                continue 'inner;
            }
        };
    }
}

Thanks a lot!

>Solution :

Even without that, it wouldn’t work, because your println statement return () which you cannot assign to u32. Even if it succeeded, the lifetime of command is limited to the loop so you can’t use it after breaking out.

For your particular problem, I think the break val syntax can help you :

let command: u32 = loop {
    println!("Input 1 to throw the dice");

    let mut command = String::new();

    io::stdin()
        .read_line(&mut command)
        .expect("Failed to read line");
    match command.trim().parse::<u32>() {
        Ok(res) => break res,
        Err(_) => println!("invalid")
    };
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading