What's the reason behind this design of rust?

Why does the below code won’t compile ?

I know that you can’t leave any variable partially initialised but i do initialise in the next line, So is it that it’s difficult for compiler to infer that ( though i don’t really think that ) or is it for some other reason that i don’t understand

This code is from Too Many Linked Lists Book

pub fn push(&mut self, elem: i32) {
    let new_node = Box::new(Node {
        elem: elem,
        next: self.head,
    });

    self.head = Link::More(new_node);
}

>Solution :

The text literally tells you why:

In principle, this is something Rust could actually accept, but it won’t (for various reasons — the most serious being exception safety).

And while in many cases rustc can be over-cautious, that’s not the case here:

let node = Node { elem: elem, next: self.head };

let new_node = Box::new(new_node); // can panic, leaving `self` in an invalid state

self.head = Link::More(new_node);

Leave a Reply