Assigning to uninitialised struct


#1

I have a hard time to understand why it is possibe to assign fields of an uninitialised struct like this:

struct Point {x: u32, y: u32}

let mut p: Point;
p.x = 0;

Why does this not throw a compilation error? On the other hand, is there any case where I actually want to assign to an uninitialised struct?


#2

In the case where you set the elements individually, no, since you can’t then pass p to another function. You will get a “use of possibly uninitialized variable” error.

However you might want to initialize p to something based off a conditional like:

struct Point {x: u32, y: u32}

let mut p: Point;

if a == b {
    p = Point { x: 0, y: 0 };
} else { 
    p = Point { x: a, y: b };
}

#3

Thanks for your answer. But do you know why there is no compilation error?


#4

my guess, rust is pedantic. And there is nothing unsafe about writing to allocated but uninitialized memory. So rust doesn’t complain. I see it as similar to raw pointers. It is safe to make one, just not to read one. Pedantic, but technically correct. Just a noobs 0.02.


#5

Yeah, as @Eh2406 said, this is useless, but does not cause any problems, so it’s OK that it does not report an error. In general, Rust preciselly tracks the controlflow to check that every value is initialized, so in theory you might be able to do something like

struct Point {x: u32, y: u32}

let mut p: Point;
p.x = 0;
p.y = 92;

// p is fully initialized, so can use it from now on. 

This is not currently implemented though, but is a possible extension of the language. See https://github.com/rust-lang/rust/issues/21232 for more details.


#6

Thanks, that makes sense. But I agree with mrubek that it at least should become a warning.


#7

filed under https://github.com/Manishearth/rust-clippy/issues/1058