我刚开始学习Rust,并尝试编写一些基本算法,以了解这种语言。我尝试编写一个函数,给定一个int类型的数字,将其转换为由bool值表示的二进制形式,其中true表示1,false表示0(如果有更好的“位”类型建议,我也可以接受)。目前我的实现如下:
这段代码无法通过编译,会出现以下错误:
fn to_base_2(num: int) -> List<bool> {
fn to_base_2_acc(num: int, acc: List<bool>) -> List<bool> {
if num == 0 {
return acc;
} else {
let bit = (num % 2) == 0;
let new_acc = Cons(bit, acc);
return to_base_2_acc(num / 2, new_acc);
}
}
to_base_2_acc(num, Nil);
}
这段代码无法通过编译,会出现以下错误:
main.rs:20:28: 20:31 error: mismatched types: expected `@extra::list::List<bool>` but found `extra::list::List<bool>` (expected @-ptr but found enum extra::list::List)
main.rs:20 let new_acc = Cons(bit, acc);
^~~
然而,通过在 List
前面去掉 @
来更新代码将导致以下结果:
main.rs:15:34: 15:45 error: The managed box syntax is being replaced by the `std::gc::Gc` and `std::rc::Rc` types. Equivalent functionality to managed trait objects will be implemented but is currently missing.
main.rs:15 fn to_base_2_acc(num: int, acc: @List<bool>) -> List<bool> {
^~~~~~~~~~~
main.rs:15:34: 15:45 note: add #[feature(managed_boxes)] to the crate attributes to enable
main.rs:15 fn to_base_2_acc(num: int, acc: @List<bool>) -> List<bool> {
^~~~~~~~~~~
main.rs:25:21: 25:25 error: The managed box syntax is being replaced by the `std::gc::Gc` and `std::rc::Rc` types. Equivalent functionality to managed trait objects will be implemented but is currently missing.
main.rs:25 to_base_2_acc(num, @Nil);
^~~~
main.rs:25:21: 25:25 note: add #[feature(managed_boxes)] to the crate attributes to enable
main.rs:25 to_base_2_acc(num, @Nil);
^~~~
我正在使用rustc 0.9-pre,这个版本的编译器中链表不能使用吗?
@
语法,但是在您的代码顶部添加#[feature(managed_boxes)]应该可以消除该错误。 - snf