I am trying to build a C compiler in Rust for a university course.
It's my first time using Rust and I am just a beginner. I know that building a compiler is a difficult task but hopefully it won't be that hard
The parser struct has a token that represents the token that is currently read.
When reading tokens the parser should create the AST of the program.
The problem I have is here
cannot move out of `self.token` as enum variant `Identifier` which is behind a shared reference
--> src/main.rs:12:15
|
12 | match self.token {
| ^^^^^^^^^^
13 | SimpleToken::Identifier(s) => {
| -
| |
| data moved here
| move occurs because `s` has type `String`, which does not implement the `Copy` trait
|
help: consider borrowing here
|
12 | match &self.token {
The full code:
struct SimpleParser {
token: SimpleToken,
}
enum Expression {
VarDefinition(String, u32)
}
impl SimpleParser {
fn match_token(&self) -> Expression {
// let token = SimpleToken::Identifier("hey".to_string());
// problem is here.
match self.token {
SimpleToken::Identifier(s) => {
Expression::VarDefinition(s, 2)
}
_ => panic!("Bad")
}
}
}
enum SimpleToken {
Identifier(String)
}
fn main() {
}
What I want
I do not want to borrow the value of the token, I want to simply take ownership and move the String from the Identifier
enum to the VarDefinition
enum.
Interestingly enough, if I have a local variable and I match on it then the code compiles.
fn match_token(&self) -> Expression {
let token = SimpleToken::Identifier("ana".to_string());
match token {
SimpleToken::Identifier(s) => {
Expression::VarDefinition(s, 2)
}
_ => panic!("Bad")
}
}
I don't really understand how the borrow checker works and what the issue is here.
Why does it work with a local variable but not with a variable of the struct.
I guess the reason could be that after I move the String from the Identifier
to VarDefinition
it is possible to access self.token
and read moved data.