I am trying to write an Interpreter in Rust. I am new in Rust but not new to programming and have some aquaintence 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
}
}
}
But it didn't work because if
moves the value of the borrowed content (the compiler says so). So how can avoid this situation? and why if
has to move the value?
Aucun commentaire:
Enregistrer un commentaire