Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Problems with modifying hash map in a trait
I have a structure I'm planning to hand out in function calls instead a OnceCell as a global variable. I have a hash map in the structure which contains information needed by functions that get called. The trait contains functions to add to the hash map and convert the contents to a vector. I decided to get the information as a vector as I was unable to iterate the hash map. I found example of doing this but none worked. So I am trying to get the following code to work but it looks like having the information in the trait results in borrow problems. Can anyone suggest what I am doing wrong or it there a better way.
Here is the test code I am playing with -
use std::collections::HashMap;
#[derive(Debug)]
struct A {
aa: String,
}
struct Mapper {
map: HashMap<String, A>,
}
impl Mapper {
fn new() -> Mapper {
Mapper { map: HashMap::new(), }
}
fn convert(&self) -> Vec<&A> {
let mut vec: Vec<&A> = Vec::from_iter(self.map.values());
vec
}
fn insert(mut self, name: String, item: A) {
self.map.insert(name, item);
}
}
fn main() {
let mapper= Mapper::new();
let myaa = A { aa: "aa".to_string() };
let keya = "aa".to_string();
mapper.insert(keya, myaa);
let x = mapper.convert();
println!("{:?}", x);
}
fn convert(mapp: &HashMap<String, A>) -> Vec<&A> {
let vec3 = Vec::from_iter(mapp.values());
return vec3;
}
6 posts - 4 participants
🏷️ rust_feed