Hacker News new | ask | show | jobs
by pwdisswordfishq 5 days ago
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.
2 comments

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.

Rust doesn’t have implementation inheritance. If it did, it would need a constructor-like concept as well.
With guaranteed RVO you could do something like this (pseudo-C):

   struct FooBase { ... }
   fn make_foo_base(...) -> FooBase
   struct Foo { base : FooBase; ... }
   fn make_foo(args...) -> Foo {
      return { .base = make_foo_base(...), ... }
   }
How is it ensured that make_foo will actually call make_foo_base?
Because it needs a FooBase to give as the value for .base or the struct initialization isn't valid because it doesn't give values for all the members?
You are right, sorry, lost track or the thread.