#Problems with struct mutability

5 messages · Page 1 of 1 (latest)

deep star
#

(parse_precedence is the important one btw, just provided the rest for context)
Err:
cannot borrow *self as mutable because it is also borrowed as immutable
mutable borrow occurs hererustcClick for full compiler diagnostic
compiler.rs(203, 33): immutable borrow occurs here
compiler.rs(206, 39): immutable borrow later used here

tranquil pivot
#

-errors

charred valveBOT
#

Run cargo check in a terminal

Note: If using rust analyzer you can click the "click for full compiler diagnostic" link in your editor.

Please post the full output of the above command, including the error title and any help or notes. An example of how this looks is:

error[E0308]: mismatched types
 --> src/main.rs:3:17
  |
3 | let foo: &i32 = bar;
  |          ----   ^^^ expected `&i32`, found integer
  |          |
  |          expected due to this
  |
help: consider borrowing here
  |
3 | let foo: &i32 = &bar;
  |                 +

When posting the error put it in a code block so it has nice formatting:
```rust
// error from cargo check here
```

Please do not post a screenshot. If the output is to long then use a paste tool like https://paste.rs/web

deep star
night valve
#

For the first error, because the advance method overwrites self.previous anyways, you could use self.previous.take() to get the previous token (which replaces it with None):

if let Some(previous) = self.previous.take() {
    self.advance();
    // previous can still be used here because we moved it instead of taking a reference

For the second error, it looks to me like it accidentally caught a logic error in the parser. This code:

if let Some(current) = &self.current {
    while precedence <= self.get_rule(&current.get_type()).precedence {
        // ...

is an endless loop. It gets the operator once and then tests its precedence over and over again. I think you want this instead, which should compile:

while let Some(current) = &self.current {
    if precedence > self.get_rule(&current.get_type()).precedence {
        break;
    }
    // ...

Also, in the advance method, you can avoid another copy by using .take() again. In this code:

self.previous = self.current.clone();
loop {
    self.current = Some(self.scanner.scan_token());

self.current is immediately overwritten after cloning it, so you can replace the .clone() with .take() to avoid cloning each token