gpt4 book ai didi

linked-list - 在 Rust 中使用 List

转载 作者:行者123 更新时间:2023-11-29 08:06:58 24 4
gpt4 key购买 nike

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

最佳答案

您需要 @是因为 extra::list::List 定义为 Cons需要 @List<T>作为第二个值。

但是,正如您发现的那样,尝试添加 @的抛出特征门错误。正如 snf 评论的那样,您可以添加

#[feature(managed_boxes)];

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

关于linked-list - 在 Rust 中使用 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com