Setvizan
Setvizan

Reputation: 48

Rust giving error for Option<usize> when using variable inside of method

I am very new to Rust and decided my first program to be a brainfuck interpreter. I plan on using jump tables as the solution for the loops. However I decided to rewrite the method to make it look better (for my tastes) and i got an error that I can't quite understand why

Code before causes no errors:

fn process_jumps(jump_map: &mut Vec<usize>, instructions: &Vec<Inst>){
    let mut stack: Vec<usize> = Vec::new();
    for (i, inst) in instructions.iter().enumerate() {
        match inst {
            Inst::LoopOpen => stack.push(i),
            Inst::LoopClose => {
                jump_map[i] = stack.pop();
                jump_map[jump_map[i]] = i;
            }
            _ => ()
        }
    }
}

Code after has an error (marked in code):

fn process_jumps(instructions: &Vec<Inst>) -> Vec<usize> {
    let mut jump_table: Vec<usize> = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    for (i, inst) in instructions.iter().enumerate() {
        match inst {
            Inst::LoopOpen => stack.push(i),
            Inst::LoopClose => {
                jump_table[i] = stack.pop(); // expected `usize`, found `Option<usize>`
                jump_table[jump_map[i]] = i;
            }
            _ => ()
        }
    }
    return jump_table;
}

My main question is why my code before didn't need me to check the optional?

Upvotes: 0

Views: 205

Answers (1)

at54321
at54321

Reputation: 11756

Vec's pop() method returns Option<T>, not T.

You need to get the usize value from inside that Option, just make sure you've handled the None case correctly. When you are sure None is not possible, the simplest thing you could do is to unwrap() it.

Neither of your examples should really compile, as they both try to assign Option<usize> to a Vec<usize>.

Upvotes: 4

Related Questions