In Chapter 4 - Section Hashsets, the code in the example on caching doesn't compile, presumably because the cache is defined outside a function. I modified it as follows for it to compile. Also note that HashSet::insert() seems to take a single argument, whereas the example code provides two arguments. Not sure if my edit produces an erroneous result.
use std::collections::HashSet;
fn expensive_computation(input: i32) -> i32 {
input * 2
}
fn get_or_compute(input: i32, cache: &mut HashSet<i32>) -> i32 {
if cache.contains(&input) {
*cache.get(&input).unwrap()
} else {
let result = expensive_computation(input);
cache.insert(input);
result
}
}
fn main() {
let mut cache: HashSet<i32> = HashSet::new();
get_or_compute(1, &mut cache);
get_or_compute(2, &mut cache);
println!("{:?}", cache);
get_or_compute(3, &mut cache);
get_or_compute(4, &mut cache);
get_or_compute(5, &mut cache);
println!("{:?}", cache);
println!("{:?}", get_or_compute(2, &mut cache));
println!("{:?}", get_or_compute(4, &mut cache));
}
In Chapter 4 - Section Hashsets, the code in the example on caching doesn't compile, presumably because the cache is defined outside a function. I modified it as follows for it to compile. Also note that HashSet::insert() seems to take a single argument, whereas the example code provides two arguments. Not sure if my edit produces an erroneous result.