2

I am trying to write an interpreter in Rust. I am new to Rust but not new to programming and have some acquaintance with Python. I am trying to translate this piece of Python code to Rust.

def eat(self, token_type):
    # compare the current token type with the passed token
    # type and if they match then "eat" the current token
    # and assign the next token to the self.current_token,
    # otherwise raise an exception.
    if self.current_token.type == token_type:
        self.current_token = self.get_next_token()
    else:
        print("Mismatched types!")

And my Rust code is

/// The structs and enums
#[derive(Debug, Eq, PartialEq)]
enum TokenType {
    INTEGER,
    PLUS,
    EOF,
}

#[derive(Debug, Eq, PartialEq)]
struct Token {
    ttype: TokenType,
    value: Option<char>,
}

#[derive(Debug)]
struct Interpreter {
    text: String,
    pos: usize,
    current_token: Option<Token>,
}

impl Interpreter {
    pub fn get_next_token(&mut self) -> Option<Token> {
        // lexing, parsing, tokenizing
    }


    // The code I wrote for `eat`
    pub fn eat(&mut self, ttype: TokenType) {
        if self.current_token.unwrap().ttype == ttype {
        // ^^^ can't move out of borrowed content
            self.current_token = self.get_next_token();
        } else {
            // Some error handling
        }
     }
 }

It didn't work because if moves the value of the borrowed content (the compiler says so). How can I avoid this situation? Why if has to move the value?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

0 Answers0