2021-07-18

How to avoid a double borrow error in struct method

I'm newish to Rust and I'm trying to figure out how to fix the Trader.gateway_client method in the snippet below. It is caused by a double borrow of a mutable. What would be the correct way to fix the code (without cloning the self.gateway string before).

use std::collections::{HashMap};


pub struct GatewayClient {
    gateway: String,
    strategy: String,
}


pub struct Trader {
    gateway_clients: HashMap<String, GatewayClient>,
    strategy: String,
}


impl GatewayClient {
    pub fn new(gateway: &str, strategy: &str) -> Self {
        GatewayClient {
            gateway: String::from(gateway),
            strategy: String::from(strategy),
        }
    }
}


impl Trader {
    pub fn new(strategy: &str) -> Self {
        Trader {
            gateway_clients: HashMap::default(),
            strategy: String::from(strategy),
        }
    }

    pub fn gateway_client(&mut self, gateway: &str) -> &mut GatewayClient {
        self.gateway_clients.entry(String::from(gateway)).or_insert_with(|| {
            GatewayClient::new(gateway, &self.strategy)
        })
    }
}

The error thrown by the compiler is

63 |       pub fn gateway_client(&mut self, gateway: &str) -> &mut GatewayClient {
   |                             - let's call the lifetime of this reference `'1`
64 |           self.gateway_clients.entry(String::from(gateway)).or_insert_with(|| {
   |           --------------------                                             ^^ immutable borrow occurs here
   |           |
   |  _________mutable borrow occurs here
   | |
65 | |             GatewayClient::new(gateway, &self.strategy)
   | |                                          ------------- second borrow occurs due to use of `self` in closure
66 | |         })
   | |__________- returning this value requires that `self.gateway_clients` is borrowed for `'1`


from Recent Questions - Stack Overflow https://ift.tt/3wRhMZI
https://ift.tt/eA8V8J

No comments:

Post a Comment