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 convert Option<&u8> to u8

i want to convert Option<&u8> to u8 so i will be able to print it

my code:

fn main() {
    let v : Vec<u8> = vec![1, 2, 3, 4, 5];

    let out_of_range = &v[100];
    let out_of_range = v.get(100);
    match out_of_range{
        Some(&u8) => println!("data out of range: {}", out_of_range),
        None => println!("bruh"),
    }
}

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 :

Your match statement needs the introduction of a binding, not a type (the &u8 you used was not expected here).

Here Some(val) matches with something which is an Option<&u8>, thus val is a binding to the embedded &u8 (if not None, of course).

The example explicitly dereferences val as an illustration, and highlights the fact that val is not an u8 but a reference, but it’s not required for the following operation (printing).

fn main() {
    let v: Vec<u8> = vec![1, 2, 3, 4, 5];
    for idx in [2, 20, 4] {
        let at_index = v.get(idx);
        match at_index {
            Some(val) => {
                // val has type &u8
                let copy_of_val = *val; // not required, just for the example
                println!("at {} --> {}", idx, copy_of_val);
            }
            None => println!("no value at {}", idx),
        }
    }
}
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