Skip to content

Chapter 4 - Section Hashsets - cache is not defined in a function #7

@glafrance

Description

@glafrance

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));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions