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);
}