0

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();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    [The duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0c1354df68912077cc5153403d8424a6) – Shepmaster Dec 09 '20 at 16:36
  • @Shepmaster, Thanks for your answer, one more question does this come in Rust's book? . I hardly go into the hashmaps topic but I can't find anything related to your answer – Angel Judath Alvarez Dec 09 '20 at 16:54
  • No, this isn't really discussed because global variables are generally discouraged. The closest is a discussion about [unsafe mutable statics](https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable). once_cell / lazy-static are both safe abstractions on top of the unsafe building blocks. – Shepmaster Dec 09 '20 at 17:41

0 Answers0