fn main() {
let mut indexer_customer = IndexerCustomer::new();
let customer = Customer::new(1, "Martin".to_string(), "New York".to_string());
indexer_customer.insert(customer);
let customer = Customer::new(2, "Johnny".to_string(), "Austin".to_string());
indexer_customer.insert(customer);
}
But I'm getting the error:
error[E0499]: cannot borrow `indexer_customer` as mutable more than once at a time
--> src/main.rs:52:5
|
49 | indexer_customer.insert(customer);
| ---------------- first mutable borrow occurs here
...
52 | indexer_customer.insert(customer);
| ^^^^^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
error: aborting due to previous error
I can't understand where the borrow is occurring. I'm not using "&" explicitly.
This is due to the 'a in &'a mut self. You never want that because the 'a lifetime is guaranteed to contain the entire lifetime of the struct, which means borrowing self for the 'a lifetime borrows it at least until the end of the struct's lifetime. Remove it.
After looking at your code closer, I see why the compiler led you astray: you are trying to create a self-referential struct.
When you have a lifetime <'a> on a struct, that lifetime denotes references to values stored outside of the struct. If you try to store a reference that points inside the struct rather than outside, you will run into a compiler error when the compiler notices you lied to it.
First, thank you very much! I learned a lot with your explanation!
Well, Rust doesn’t allow self ref is very sad. My project is memory-critical over performance, then I need to avoid cloning always when possible. Your response inspired me to push the red button (aka Rc<>). And appears that work very fine too me… that’s the result:
I would go as far as saying that Pin doesn't do anything. It's a type-system way of saying "Don't touch this! Unsafe stuff may be inside it!". It helps isolate data that is unsafe to access, but it won't automatically make it safe for you.