]> git.lizzy.rs Git - rust.git/commitdiff
Style: default over new
authorAleksey Kladov <aleksey.kladov@gmail.com>
Wed, 14 Oct 2020 18:02:03 +0000 (20:02 +0200)
committerAleksey Kladov <aleksey.kladov@gmail.com>
Wed, 14 Oct 2020 18:02:03 +0000 (20:02 +0200)
docs/dev/style.md

index 59067d23460f1b5d71edac7b9e528d75933b3448..435de63e3bd4ec63871bd5e3bb8a69501d869b62 100644 (file)
@@ -186,6 +186,31 @@ impl Person {
 }
 ```
 
+## Constructors
+
+Prefer `Default` to zero-argument `new` function
+
+```rust
+// Good
+#[derive(Default)]
+struct Foo {
+    bar: Option<Bar>
+}
+
+// Not as good
+struct Foo {
+    bar: Option<Bar>
+}
+
+impl Foo {
+    fn new() -> Foo {
+        Foo { bar: None }
+    }
+}
+```
+
+Prefer `Default` even it has to be implemented manually.
+
 ## Avoid Monomorphization
 
 Rust uses monomorphization to compile generic code, meaning that for each instantiation of a generic functions with concrete types, the function is compiled afresh, *per crate*.