In Rust (version 1.x) I want to use elements of a collection inside a loop such as the example below (which recors the characters it has seen and does something when it spots a repeated char) where the collection is defined inside the function and only used by the loop.
fn do_something(word:&str) -> u32 {
let mut seen_chars = HashMap::new();
let mut answer : u32 = 0;
for (i,c) in word.chars().enumerate() {
let char_str = Box::new(c.to_string());
match seen_chars.get(&char_str) {
Some(&index) => {
answer = answer + index;
},
None => {seen_chars.insert(char_str,i);}
};
}
answer
}
In order to store references to c in my hashmap (which I have declared outside the loop) I need to box c and allocate it on the heap. This feels inefficent and like I must be doing something wrong. I wondered if using explicit lifetimes would be a better way to do things, below is my best attempt but I can't get it to compile.
fn do_something<'a>(word:&str) -> u32 {
let mut seen_chars = : &'a HashMap<&str,usize> = &HashMap::new();
let mut answer : u32 = 0;
for (i,c) in word.chars().enumerate() {
let char_str = &'a str = &c.to_string();
match seen_chars.get(&char_str) {
Some(&index) => {
answer = answer + index;
},
None => {seen_chars.insert(char_str,i);}
};
}
answer
}
When I try compiling I get "error: borrowed value does not live long enough" with an indication that "&HashMap::new()" is the problem. Can I use lifetime specification to solve this issue or am doing things the wrong way here?