我正在尝试在 Rust 中记忆递归 collatz 序列函数,但是我需要记忆值的哈希图来在单独的函数调用中保留其内容。有没有一种优雅的方法可以在 Rust 中做到这一点,或者我是否必须在 main 中声明 hashmap 并每次将其传递给函数?我相信每次调用该函数时,哈希映射都会被重新声明为空映射。这是我的代码:
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);
}
附带说明一下,为什么当我在 HashMap 中插入和取出项目时需要添加所有 & 和 * ?我这样做是因为编译器抱怨并添加它们修复了它,但我不确定为什么。我不能只按值传递吗?谢谢。
您可以使用线程本地 http://doc.rust-lang.org/std/thread/struct.LocalKey.html用于线程局部静态。
thread_local! (static COLLATZ_MEM: HashMap<i32, i32> = HashMap::new());
fn collatz(n: i32) -> i32 {
COLLATZ_MEM.with (|collatz_mem| {
0 // Your code here.
})
}
附:还有一个优秀的惰性静态 https://github.com/Kimundi/lazy-static.rs可用于真正的全局静态缓存的宏。Here http://mainisusuallyafunction.blogspot.ru/2014/10/a-taste-of-rust-yum-for-cc-programmers_29.html就是一个例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)