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 set specific return type to scope in rust, if even possible?

I have this scope in the print macro that tries to find an integer between 1 and 1 billion. If it fails, it should panic.

fn main() {
    println!(
        "{}",
        {
            for i in 0..1000000000 {
                if i == 100 {
                    Some(i)
                }
            }
            None
        }
        .unwrap()
    );
}

At the line with Some(i) it has an error:

mismatched types
expected unit type `()`
        found enum `Option<{integer}>`

How can I fix this?

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

>Solution :

If you want to use if as an expression you have to provide an else as well.
I think you want something else though, break out of that block early.
You can do that with the recently stabilized named blocks:

fn main() {
    println!(
        "{}",
        'bl: {
            for i in 0..1000000000 {
                if i == 100 {
                    break 'bl Some(i);
                }
            }
            None
        }
        .unwrap()
    );
}
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