Is it possible to access the values of a HashMap
and edit them from any function?
That is, declare a new HashMap
only once and in whatever function you need to call its get()
or insert()
method to update or obtain a value.
This is what I tried:
use std::collections::HashMap;
#[derive(Clone)]
struct New<'a> {
hash: HashMap<&'a str, &'a str>,
}
impl<'a> New<'a> {
fn new() -> New<'a> {
New {
hash: HashMap::new(),
}
}
fn reference(&mut self) -> New<'a> {
New { hash: self.hash }
}
fn join(&mut self, key: &'a str, value: &'a str) {
self.hash.insert(key, value);
}
}
fn add_one() {
let mut n = New::new();
n.join("hi", "jo");
n.join("h1", "h2");
println!("{:?}", n.hash);
}
fn add_two() {
let s = New::reference();
s.join("hi2", "hi2");
}
fn main() {
add_one();
add_two();
}