Hacker News new | ask | show | jobs
by tyg13 708 days ago
You're mistaken. Rust does not require you to define all constructors. Rust does not have constructors.

All structs in Rust must be initialized using brace syntax, e.g. `Foo { bar: 1, baz: "" }`. This is commonly encapsulated into static functions (e.g. `Foo::new(1, "")`) that act similarly to constructors, but which are not special in any way compared to other functions. This avoids a lot of the strangeness in C++ that arises from constructors being "special" (can't be named, don't have a return type, use initializer list syntax which is not used anywhere else).

This combined with mandatory move semantics means you also don't have to worry about copy constructors or copy-assignment operators (you opt into copy semantics by deriving from Clone and explicitly calling `.clone()` to create a copy, or deriving from Copy for implicit copy-on-assign) or move constructors and move-assignment operators (all non-Copy assignments are moves by default).

It's actually rather refreshing, and I find myself writing a lot of my C++ code in imitation of the Rust style.

1 comments

> You're mistaken. Rust does not require you to define all constructors. Rust does not have constructors.

I don't think you managed to understand what I actually said, and consequently you wrote a whole wall of text that's not related to the point I made.

Your post starts with the flawed assumption that you have to define constructors in Rust, and then your own wall of text (ironically longer than mine) about avoiding boilerplate which doesn't apply to Rust. I'm not sure you understood my point.
> Your post starts with the flawed assumption that you have to define constructors in Rust (...)

I did not. Read what I wrote.

Just to further illustrate what I'm saying, are you really trying to say that

``` //explicitly annotating this struct is default initializable and copyable #[derive(Default, Copy, Clone)] struct Foo { ... } ```

is actually worse than

``` struct Foo {...}; // rule of zero, copy/move/default are defined/deleted based arcane rules predicated on the contents of Foo ```

> Just to further illustrate what I'm saying, are you really trying to say that (...)

If you read what I wrote you'll notice I was pointing out the absurdity of claiming that being forced to write each and every single factory method/constructor is somehow better and simpler than allowing the compiler to write them for us for trivia classes but still having the compiler step off when we opt to write each and every single factory method/constructor ourselves.