gpt4 book ai didi

rust - rust 迹所有权-由于存在 “behind a shared reference”而无法移动

转载 作者:行者123 更新时间:2023-12-03 11:31:39 29 4
gpt4 key购买 nike

我正在学习Rust并在“链表”上进行练习,因此我想找到一种最终不涉及.clone()的解决方案。

这是我可以拿出的最小的有用的MVP代码(Rust Playground):

#![allow(unused)]
fn main() {
let v: Option<Box<ListNode>> = None;

println!("{:?}", v);
let result2 = get_nth_node(v, 3);
println!(" --> {:?}", result2);
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}

fn get_nth_node(head: Option<Box<ListNode>>, n:usize) -> Option<Box<ListNode>> {
if head.is_none() {
return None;
}

let mut count = 1;
let mut ptr: &Option<Box<ListNode>> = &head;
while count < n {
count += 1;
match ptr {
None => return None,
Some(v) => ptr = &v.next
}
}
return (*ptr);
}

这会在移动和借入时产生​​错误:
error[E0507]: cannot move out of `*ptr` which is behind a shared reference
--> src/main.rs:30:12
|
30 | return (*ptr);
| ^^^^^^
| |
| move occurs because `*ptr` has type `std::option::Option<std::boxed::Box<ListNode>>`, which does not implement the `Copy` trait
| help: consider borrowing the `Option`'s content: `(*ptr).as_ref()`

我知道为什么更改函​​数以返回 (*ptr).clone()可行,但似乎是多余的。

我的两个主要问题:
1. *ptr背后的共享引用具体是什么?
2.从概念上讲,是否有更好的方法可以在Rust中使用它?

最佳答案

What specifically is the shared reference that *ptr is behind?


ptr是共享的(不可变的)引用:

let mut ptr: &Option<Box<ListNode>> = &head;

*ptr在该引用的后面。

Is there a better way, conceptually, to work with this in Rust?



好吧,您不能使用引用,因为您要按值获取列表,因此会消耗它:

fn get_nth_node(mut head: Option<Box<ListNode>>, n:usize) -> Option<Box<ListNode>> {
let mut count = 1;
while count < n {
count += 1;
match head {
None => return None,
Some(v) => head = v.next
}
}
return head;
}

或者,您可以使用refs(这可能是一个更好的主意):


fn get_nth_node(mut head: Option<&ListNode>, n:usize) -> Option<&ListNode> {
let mut count = 1;
while count < n {
count += 1;
match head {
None => return None,
Some(v) => head = v.next.as_ref().map(Box::as_ref)
}
}
head
}

关于rust - rust 迹所有权-由于存在 “behind a shared reference”而无法移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61111543/

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