Remix.run Logo
▲ pwdisswordfishq 3 hours 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.

▲steveklabnik 3 hours ago | parent | next [-]

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 3 hours ago | parent | prev [-]

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

▲gpderetta an hour ago | parent [-]

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(...), ... }
   }