Storing a variable in various function calls in rust

I am trying to memoize a recursive collatz sequence function in rust, however I need a hash map of memoized values ​​to save its contents in different function calls. Is there an elegant way to do this in rust, or should I declare a hash map basically and pass it functions every time? I believe the hashmap is updated as an empty map every time I call a function. Here is my code:

fn collatz(n: int) -> int {
    let mut map = HashMap::<int, int>::new();
    if map.contains_key(&n) {return *map.get(&n);}
    if n == 1 { return 0; }
    map.insert(n, 
        match n % 2 {
            0 => { 1 + collatz(n/2) }
            _ => { 1 + collatz(n*3+1) }
        }
    );
    return *map.get(&n);
}

On the side of the note, why do I need to add everything and and * when I insert and pull elements from the HashMap? I just did it because the compiler complained and added that I fixed it, but I'm not sure why. Can't I get past the meaning? Thank.

+4
2

thread_local .

thread_local! (static COLLATZ_MEM: HashMap<i32, i32> = HashMap::new());
fn collatz(n: i32) -> i32 {
    COLLATZ_MEM.with (|collatz_mem| {
        0  // Your code here.
    })
}

P.S. lazy-static, . .

+3

Rust "" , C, . , , collatz .

, ( ), ( ). ints, API .

+3

Source: https://habr.com/ru/post/1534184/


All Articles