首页 > 解决方案 > 在 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 中实现这个算法的正确方法是什么?

标签: rust

解决方案


推荐阅读