Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading