【问题标题】:Using List<T> in Rust在 Rust 中使用 List<T>
【发布时间】:2013-12-26 20:21:45
【问题描述】:

我刚刚开始使用 Rust,并尝试编写一些基本算法来感受该语言。我在这里的尝试是编写一个函数,给定int 将其转换为由bool 值的链接列表表示的二进制形式,true 用于1false 用于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。链表在这个版本的编译器中不起作用吗?

【问题讨论】:

  • 随着 github.com/mozilla/rust/pull/10576 的登陆, Gc 正在替换 @ 语法,但在代码顶部添加 #[feature(managed_boxes)] 应该可以消除该错误。跨度>

标签: linked-list rust


【解决方案1】:

您需要@,因为extra::list::List 的定义使得Cons 需要@List&lt;T&gt; 作为第二个值。

但是,正如您所发现的,尝试添加 @ 会引发功能门错误。正如 snf 所评论的,您可以添加

#[feature(managed_boxes)];

到根 crate 文件的顶部以启用 @ 的使用。

【讨论】:

  • “managed_boxes”是一项即将消失的旧功能还是一项新功能?
  • @T.Stone:它们是一个即将消失的旧功能。它们将被库类型 std::gc::Gc&lt;T&gt;std::rc::Rc&lt;T&gt; 替换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多