gpt4 book ai didi

rust - 尝试 `use` 枚举结果为 "unresolved import"

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

Following the Rust example on enum :

// Allow Cons and Nil to be referred to without namespacing
use List::{Cons, Nil};

// A linked list node, which can take on any of these two variants
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(uint, Box<List>),
// Nil: A node that signifies the end of the linked list
Nil,
}

// Methods can be attached to an enum
impl List {
// Create an empty list
fn new() -> List {
// `Nil` has type `List`
Nil
}

// Consume a list, and return the same list with a new element at its front
fn prepend(self, elem: uint) -> List {
// `Cons` also has type List
Cons(elem, box self)
}

// Return the length of the list
fn len(&self) -> uint {
// `self` has to be matched, because the behavior of this method
// depends on the variant of `self`
// `self` has type `&List`, and `*self` has type `List`, matching on a
// concrete type `T` is preferred over a match on a reference `&T`
match *self {
// Can't take ownership of the tail, because `self` is borrowed;
// instead take a reference to the tail
Cons(_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
}
}

// Return representation of the list as a (heap allocated) string
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}

fn main() {
// Create an empty linked list
let mut list = List::new();

// Append some elements
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);

// Show the final state of the list
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}

将其保存为名为 test.rs 的文件并使用 rustc test.rs 进行编译会给出错误:

test.rs:2:12: 2:16 error: unresolved import `List::Cons`. Cannot import from a trait or type implementation
test.rs:2 use List::{Cons, Nil};
^~~~
test.rs:2:18: 2:21 error: unresolved import `List::Nil`. Cannot import from a trait or type implementation
test.rs:2 use List::{Cons, Nil};
^~~
error: aborting due to 2 previous errors

然而,如果您在链接到的在线站点上运行它,它就可以正常工作。我不明白为什么这对我不起作用。我需要最新的(每晚)Rust 吗?

rustc --version 显示我有 0.12.0-dev 版本。

最佳答案

是的,你需要每晚。如果我没记错的话,命名空间枚举是在 0.12 发布后引入的。

一般来说,除非你有充分的理由不这样做,否则你应该使用夜间事件。那是大多数人使用的。如果你不这样做,你就会与 Cereal 作斗争——大多数活跃的库都会随着 nightlies 的发布而定期更新。

关于rust - 尝试 `use` 枚举结果为 "unresolved import",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725748/

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