rust - 在 Rust 中迭代地构建单链表
问题描述
(这里是 Rust 新手)我想在 Rust 中创建一个单链表,方法是持有对尾部的引用并写入它。这是 C++ 中的算法:
#include <memory>
#include <string>
struct CharList {
char c;
std::unique_ptr<CharList> next;
explicit CharList(char c) : c(c) {}
};
CharList make_list(const std::string &s) {
CharList res{'a'};
auto *tail = &res.next;
for (char c : s) {
*tail = std::make_unique<CharList>(c);
tail = &(*tail)->next;
}
return res;
}
这是我在 Rust 中的尝试(Rust playground 链接)
struct CharList {
c: char,
next: Option<Box<CharList>>,
}
fn make(s:&str) -> CharList {
let mut result = CharList{
c: 'a',
next: None
};
{
let mut tail = &mut result.next;
for c in s.chars() {
let cl = CharList {
c: c,
next: None
};
mem::replace(tail, Some(Box::new(cl)))
let mut next = &mut tail.as_mut().unwrap().next;
tail = next
}
}
result
}
产生的错误是:
error[E0499]: cannot borrow `*tail` as mutable more than once at a time
--> src/main.rs:21:26
|
21 | mem::replace(tail, Some(Box::new(cl)));
| ^^^^ second mutable borrow occurs here
22 | let next = &mut tail.as_mut().unwrap().next;
| ---- first mutable borrow occurs here
...
25 | }
| - first borrow ends here
我发现第一次借用报告发生在第二次借用之后令人困惑,但我认为这是因为它们发生在循环的不同迭代中。
在 Rust 中实现这个算法的正确方法是什么?
解决方案
推荐阅读
- mongodb - 31 中大小为 1 的 Mongo 样本总是返回相同的记录
- java - Java:初学者问题:为什么我没有从这段代码中得到数字(1、4、9、16、25、36、49)[已解决]
- python - 如何根据比较两列中的值来组合熊猫数据框中的行?
- mysql - 连接到不特定的数据库名称
- typescript - 没有正确推断泛型的类型?
- json - 将 json 值转换为枚举值
- java - 如何知道 Room 的 onCreate() 回调结束
- sql - 如何使用联合获得不同的记录 postgresql
- reporting-services - SSRS 切换添加列,将报告导出到 Excel 时
- excel - 如何获取形状名称(Groupshapes 名称)