在Rust中使用List<T>

3
我刚开始学习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,这个版本的编译器中链表不能使用吗?


1
随着 https://github.com/mozilla/rust/pull/10576 的落地,Gc<T>正在取代@语法,但是在您的代码顶部添加#[feature(managed_boxes)]应该可以消除该错误。 - snf
1个回答

3
您需要使用@,因为extra::list::List的定义要求Cons需要一个@List<T>作为第二个值。
但是,正如您发现的那样,尝试添加@会引发功能门错误。正如snf评论的那样,您可以添加
#[feature(managed_boxes)];

将代码添加到根crate文件的顶部,以启用@的使用。


“managed_boxes”是一个即将到来的新功能还是一个即将被淘汰的旧功能? - T. Stone
1
@T.Stone:它们是一项旧功能,即将被淘汰。它们将被库类型 std::gc::Gc<T>std::rc::Rc<T> 替换。 - Lily Ballard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接