Integrate HashMap into struct with methods

Hi folks,

i am quite new to rust
I have successfully created a HashMap in the fn main ():

let fk_list: HashMap <&str,&str> =
     [("0101","Text1"),
      ("0201","Text2"),
.
. here come many more elements
.

      ("0203","Text3")].iter.cloned.collect();

and can access it e.g.:

let description = fk_list.get("9999").unwrap_or(&"No value");

As the HashMap is quite long and because I want to create some methods which do the unwrapping, I want to take it off the main fn and integrate it in a struct.

struct Fieldtab<'a>{
fk_list: HashMap<&'a str,&'a str>,
}

impl Fieldtab {
fn read() -> Fieldtab {
let fk_list: HashMap <&str,&str> =
[("0101","Text1"),
("0201","Text2"),
.
.
.
("0203","Text3")].iter().cloned().collect();
}
}

fn main should contain something like that:

let list = Fieldtab::read("version1");

as there will be several versions of the HashMap in the future read() should get a paramter "version1", "version2"... but this is not important for now.

let description = list.fk_list.get("8410").unwrap_or("No value");
}

Unfortunately I am quite new to rust so I am still struggling from time to time with borrowing and lifetimes':frowning:
but perhaps there ist a complete other and better way to do what I want to do..
Any ideas?
Thanks
cremofix

Please read this post for information on how you can properly format your post. All code should be in code blocks.

My main recommendation here is that your map should be using String and not &str as the key and value type. You should not need any lifetime markers whatsoever.

3 Likes

Here's an example of how to collect your literals into Strings as Alice suggested. But if it's possible to generate this hash dynamically instead hard-coding the values, that may be a better approach.

To build your data structure (or just different versions of the hash map), you could have a function somewhere like this:

fn read_data(version: &str) -> Result<HashMap<String, String>, String> {
    match version {
        "version1" => { /* Build Ok(hash_map) here */ },
        "version2" => { /* Build Ok(hash_map) here */ },
        _ => {
           let error = format!("Unrecognized version '{}'", version);
           Err(error)
        }
    }
}

(Or make it a method or associated function of your struct, whatever works best.)

Thanks alice, thanks quinedot,

succeeded in putting the HashMap into a struct and extract information with method.

I think it still will be a long and stony process to internalize all the nuances of rust :slight_smile:

1 Like

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.