Hacker News new | ask | show | jobs
by xorvoid 1598 days ago
I’ve never understood why they don’t just support partially initialized structs. They’re already doing control flow analysis for initializing variables. It seems like a natural extension to do this for aggregate types (product and sum). From a type theory perspective, a struct T is not a T in unitialized state, it’s. “partial T” that at some point gets transformed into a T. So, you’d not be able to use the T in the normal sense until the compiler can prove that all fields have been init on all possible control flow paths.

Why is this problematic? (I presume there is a fatal flaw as it seems too obvious of a solution..)

3 comments

Rust already supports partially deinitialized structs - that is, moving out of a struct field by field - and there’s no fundamental reason it can’t support partial initialization too.

Indeed, there’s an open issue for it:

https://github.com/rust-lang/rust/issues/54987

But there are a lot of desired features with open issues, so don’t expect this to be implemented anytime soon unless someone takes an interest in it.

Ah okay this makes sense. I wish I personally had the spare time to contribute this.
It's not problematic, it's just not work that's been done yet. Rust isn't finished. I bet you could get an RFC pushed through and implement it if you wanted to, it certainly is a promising idea.
As an example, in C the following is quite common:

Data dat;

dat.a = 1;

dat.b = “foobar”;

do_thing(&dat);

I seems like the compiler should be able to treat “dat” as an “maybe uninit” type until after “dat.b” gets assigned.