logoalt Hacker News

pwdisswordfishq • today at 6:40 PM • 2 replies • view on HN

Rust allows establishing invariants on its types without having a designated "constructor" concept. It accomplishes the same with the equivalent of static methods. Constructors are simply unnecessary.


Replies

steveklabnik • today at 7:09 PM

Two things make this possible, really: the first is that Rust doesn't have subclassing, so one classic reason for constructors doesn't exist. The second is Rust's privacy system, which makes it so that external users can be forbidden to use the literal syntax to create a struct. This is what lets you guard creation to preserve invariants.

One useful feature of constructors still doesn't exist, which would be the placement new style thing, but that's on its way as well, and is an optimization rather than a requirement for most cases.

layer8 • today at 7:14 PM

Rust doesn’t have implementation inheritance. If it did, it would need a constructor-like concept as well.