[英]Mutable borrow in Rust
我是 Rust 的新手,我只是在做一些练习。 有一个链表。 例如, 0->1->2->3->4 ,在索引 2 处将其切断,然后将两者反转,然后组合它们。 => 0<-1<-2 3<-4 => 2->1->0->4->3
#[derive(debug)]
struct Node{
val: usize,
next: Option<Box<Node>>,
}
impl Node {
fn new(i: usize) -> Node {
...
}
fn reverse_at(self, k: usize) -> Box<Node> {
let mut prev = None;
let mut curr = Box::new(self);
let first_part_tail = &mut curr;
let mut i: usize = 0;
while i <= k {
let next = curr.next.take();
curr.next = prev;
match next {
Some(next_node) => {
prev = Some(curr);
curr = next_node;
}
None => return curr,
}
i += 1;
}
let head = prev.unwrap();
prev = None;
loop {
let next = curr.next.take();
curr.next = prev;
match next {
Some(next_node) => {
prev = Some(curr);
curr = next_node;
}
None => {
first_part_tail.next = Some(curr);
return head;
}
}
}
}
}
我需要获取第一个节点0的可变借用,并在 function 末尾获取最后一个节点4后设置0 .next= 4 。 但是节点0的所有权已经发送给节点1 。 显然, error[E0499]: cannot borrow `curr.next` as mutable more than once at a time
发生多次,我不知道该怎么做。 这让我困扰了很长时间。 请提供任何帮助。
&
,我想这个 function 会改变节点本身。 而且我不知道如何将 self 引用更改为新节点,所以我使用了self
。 如果有人可以修改它,那也有帮助。 也许,将此 function 更改为
fn reverse_at(&mut self, k:usize){
...
}
@Ultrasaurus 感谢学习资源https://rust-unofficial.github.io/too-many-lists/ 。 现在我解决了这个问题,虽然它需要一些时间。
最终代码在这里游乐场
有点奇怪,我的LinkedNumber.head
是Node
,因为LinkedNumber
总是有一个头,可能为零,但不是 null。 也许应该是Box<Node>
。
在第 71 行,我使用ptr::read
,它将
从
src
读取值而不移动它。
mem::take
也可以。 但它需要通过trait Default
使用默认值初始化Node
。
比我使用Box::new
将节点从堆栈移动到堆。 (没有必要这样做,如果LinkedNumber.head
是Box<Node>
)
在第 73 行,标记 head 的 raw_pointer *const Node
。
在第 94 行,如果链接被分成两部分,则将*const Node
转换为*mut Node
,取消引用它,将(*ptr).next
设置为原始链接的最后一个节点。
如何测试:在第 171 行更改num.reverse_at(3)
中的数字,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.