These are chat archives for rust-lang/rust

21st
Apr 2017
Robert
@rw
Apr 21 2017 02:24
is it fair to say that serde is not for schema-versioned serialization libraries?
(i don't intend to be inflammatory; i just haven't seen anything that says what serde is not for)
VJ
@00imvj00
Apr 21 2017 04:51
if i were to write drop for my own struct stack, how should i write ?
it will store recursive Box<Stack>
VJ
@00imvj00
Apr 21 2017 05:39
finally i got the answer for the problem of recursive stuff. you need to implement drop trait for your type and do memory free iteratively
VJ
@00imvj00
Apr 21 2017 07:53
use std::mem;

#[derive(Debug)]
struct Stack {
    head: Link
}

#[derive(Debug)]
enum Link {
    Empty,
    More(Box<Node>),
}

#[derive(Debug)]
struct Node {
    value: i32,
    next: Link
}

impl Stack {
    fn new() -> Stack {
        Stack{ head: Link::Empty}
    }

    fn push(&mut self, ele: i32) {
        let new_node = Box::new(Node{
            value: ele,
            next:  mem::replace(&mut self.head, Link::Empty),
        });
        self.head = Link::More(new_node);
    }
}

impl Drop for Stack {
    fn drop(&mut self) {
        let mut cur_link = mem::replace(&mut self.head, Link::Empty);
        while let Link::More(mut boxed_node) = cur_link {
            cur_link = mem::replace(&mut boxed_node.next, Link::Empty);
        }
    }       
}    

fn main() {
   let mut stack = Stack::new();
   stack.push(10);
   stack.push(20);
   println!("{:?}", stack);
   for i in 0..10000000000 {
       stack.push(i);
   }
   println!("Done...");
}
This code works without any stackoverflow for unlimited elements.
Sherzod Mutalov
@shmutalov
Apr 21 2017 11:15
@i-m-v-j :+1:
Ross
@breadmenace_twitter
Apr 21 2017 20:30
@i-m-v-j ah, yeah, recursive dropping like that is tricky! there’s a tutorial out there which focuses on writing increasingly elaborate linked lists and explains this at some point (http://cglab.ca/~abeinges/blah/too-many-lists/book/first-drop.html)
maybe it should be in The Book (tm) if it isn’t already