I'm relatively new to Rust. I have written the code below.
The idea is that a new Client
is "uninitialized" (log_in()
hasn't been called), but certain methods (get_data()
in this example) lazily do that before they call any other Connection
methods. There is also some data foo
that is stored in the Client
and is needed by get_data()
.
struct Connection {}
impl Connection {
fn log_in(&self) { println!("Logging in"); }
fn get(&self, foo: &str) { println!("Requesting data (foo={})", foo); }
}
struct Client {
connection: Option<Connection>,
foo: String,
}
impl Client {
fn new(foo: &str) -> Client {
Client { connection: None, foo: String::from(foo) }
}
fn connection(&mut self) -> &Connection {
if self.connection.is_none() {
let c = Connection{};
c.log_in();
self.connection = Some(c);
}
&self.connection.as_ref().unwrap()
}
fn get_data(&mut self) {
self.connection().get(&self.foo)
}
}
pub fn main() {
let mut client = Client::new("foofoo");
client.get_data();
}
Unfortunately it doesn't work as I intended:
26 | self.connection().get(&self.foo)
| ---- --- ^^^^^^^^^ immutable borrow occurs here
| | |
| | mutable borrow later used by call
| mutable borrow occurs here
It seems that after calling connection()
(the call has already returned) I can't access foo
anymore?
I guess I have to approach this problem completely different?
On a side note, it also feels weird that any variable holding a Client
needs to be mut
, but I guess that's a good thing?