-2

Why does the below code not 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);
}
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
Darshan V
  • 198
  • 9
  • I think such self referencing wouldn't compile even if it was allowed to leave fields uninitialized – Alexey S. Larionov Oct 05 '22 at 10:06
  • What was the error message? – ctrl-alt-delor Oct 05 '22 at 12:02
  • Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – Jmb Oct 05 '22 at 12:22

1 Answers1

3

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);
Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Oh Okay now i get it , the Box in itself could panic , Rust has so many fine things that i never noticed , again thank you – Darshan V Oct 05 '22 at 10:42