Confusing error message

Hi,

I get an error message that I don't quite understand here (playground):

struct Foo {
    bar: Option<String>
}

impl Foo {
     fn clear(&mut self) {
        if let Some(ref mut bar) = self.bar {
            *bar.clear();
        }
    }
}

The error is:

error[E0614]: type `()` cannot be dereferenced
 --> src/lib.rs:8:13
  |
8 |             *bar.clear();
  |             ^^^^^^^^^^^^

I don't understand why I can't dereference if I'm taking a reference, and I also don't understand why the type is () in the error message. If I remove the dereference and write just bar.clear() instead of *bar.clear() everything works fine but I don't know why.

Because you are deref'ing the result of bar.clear, which is ().

Try this instead:

(*bar).clear();
1 Like

Pff I see, thanks :slight_smile:

Method calls will automatically dereference the expression before the . if necessary, so you don't need to use the * operator here. Instead, you can simply write:

bar.clear();
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.