在Rust中迭代地建立一个单链表

时间:2018-11-18 07:15:14

标签: rust

(这里是Rust noob),我想在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 link)中的尝试

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中实现此算法的正确方法是什么?

0 个答案:

没有答案