Rust: How to implement linked list?

后端 未结 1 1296
谎友^
谎友^ 2020-12-07 02:14

I thought I\'d dive into Rust by imeplementing some very simple structure & algorithms, I started with a linked list. Turns out it\'s not actually that simple. This is m

相关标签:
1条回答
  • 2020-12-07 03:03

    It looks like you're trying to walk your own list to find the final element, but you don't actually have a loop. Assuming you fix that, your issue with mutability can be fixed by using ref mut instead of ref.

    To try it myself I used a recursive implementation of add() and this works:

    fn add(&mut self, item: T) {
        match *self {
            Node(_, ref mut next) => next.add(item),
            Nil => *self = Node(item, ~Nil)
        }
    }
    

    Offhand I'm not sure how to implement this using an iterative approach, due to issues with mutable borrowing.

    0 讨论(0)
提交回复
热议问题