Unable to get past borrow issue

I have a root struct that references another struct through a HashMap which has a vector of service struct. I can't get the code to update the vector and fails with a borrow problem. This seems to be a typical way to keep data so I am having trouble seeing why updating the vector is such an issue.

use std::collections::HashMap;

#[derive(Debug, Clone)]
struct Service {
    url: String,
    token: String,
}

#[derive(Debug, Clone)]
struct Protobuf {
    name: String,
    instances: Vec<Service>,
}

impl Protobuf {
    fn add_service(&mut self, service: Service) {
        self.instances.push(service);
    }
}

#[derive(Debug, Clone)]
pub struct RootNode {
    protobuf_map: HashMap<String, Protobuf>,
}
impl RootNode {
    fn new() -> RootNode {
        RootNode {
            protobuf_map: HashMap::new(),
        }
    }
    fn add_protobuf(&mut self, key: &str, protobuf: Protobuf) {
        self.protobuf_map.insert(key.to_string(), protobuf);
    }
}

fn main() {
    let mut root = RootNode::new();

    let protobuf1 = Protobuf {
        name: "proto1".to_string(),
        instances: vec!(),
    };

    root.add_protobuf("proto1", protobuf1);

    // How to get this service struct added to proto1 vec array
    let serv = Service{
        url: "localhost:8080".to_string(),
        token: "token".to_string(),
    };

    let proto= root.protobuf_map.get("proto1").unwrap();
    println!("{:?}", proto);

   // fails at this point. 
    proto.add_service(serv);
}

You need to get a &mut _ reference to the Protobuf.

-    let proto = root.protobuf_map.get("proto1").unwrap();
+    let proto = root.protobuf_map.get_mut("proto1").unwrap();

P.s. please read the pinned code formatting guide.

Thank you for the reply. It works now!!

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.