Why does my iterative implementation of drop for a linked list still cause a stack overflow?

前端 未结 2 2092
暗喜
暗喜 2021-01-20 16:33

I am following Learning Rust With Entirely Too Many Linked Lists to write my first program in Rust. I changed the program to:

use std::mem;
         


        
2条回答
  •  感动是毒
    2021-01-20 17:05

    You are getting a stack overflow because your drop function is infinitely recursive.

    The code below:

    let mut head = mem::replace(self, List::Nil);
    

    Stores a List object in head, which will be dropped at the end of the scope. This means that, while you are dropping, you create a new list which also needs to be dropped. Repeat this enough times and you get a stack overflow.

    Note: in the tutorial you linked, they use let mut cur_link = mem::replace(&mut self.head, Link::Empty) to avoid recursion.

提交回复
热议问题