gpt4 book ai didi

rust - 如何移动拥有的指针

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

作为引用,我使用的是 Rust 0.7。

我正在尝试使用自有链表创建堆栈实现,但遇到了麻烦。

trait Stack<T> {
fn push(&mut self, item : T);
fn pop(&mut self) -> Option<T>;
}

enum Chain<T> {
Link(T, ~Chain<T>),
Break
}

impl<T> Stack<T> for ~Chain<T> {
fn push(&mut self, item : T) {
*self = ~Link(item, *self);
}
fn pop(&mut self) -> Option<T> {
None
}
}

当我尝试 rustc stack.rs 时,出现以下错误:

stack.rs:13:28: 13:34 error: cannot move out of dereference of & pointer
stack.rs:13 *self = ~Link(item, *self);
^~~~~~

我不知道我该如何克服这个问题或者我可以做些什么不同的事情来允许这个问题。似乎我应该能够在不使用托管指针的情况下创建这个数据结构,但我还没有看到很多关于这类事情的文档。

最佳答案

无论是来自 self 的赋值(我认为这包括从中构造一个新事物,如 Link(item, *self) implies a move 的情况。这意味着在构建新的 Link 使 self 变得不可用,因为:

"After a value has been moved, it can no longer be used from the source location and will not be destroyed there."

The Right Way™ 的最佳记录可能是在 this example in the stdlib 中完成的工作.这是一个双向链表,它是受管理的,但它是可变的,我希望可以免费复制。还有 list of useful container types ,也是。

不过,我确实设法让你的数据结构的这个不可变版本正常工作。

trait Stack<T> {
fn push(self, item : T) -> Self;
fn pop(self) -> Option<(T, Self)>;
fn new() -> Self;
}

#[deriving(Eq, ToStr)]
enum Chain<T> {
Link(T, ~Chain<T>),
Break
}

impl<T> Stack<T> for Chain<T> {
fn push(self, item : T) -> Chain<T> {
Link(item, ~self)
}
fn pop(self) -> Option<(T, Chain<T>)> {
match self {
Link(item, ~new_self) => Some((item, new_self)),
Break => None
}
}
fn new() -> Chain<T> {
Break
}
}

fn main() {
let b : ~Chain<int> = ~Stack::new();
println(b.push(1).push(2).push(3).to_str());
}

关于rust - 如何移动拥有的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535542/

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