From d7ece3028de09f30af4384726eca1eff2cd52dff Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Mon, 24 Aug 2020 12:19:12 +0200 Subject: Add Early Return rule to style --- docs/dev/style.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/dev/style.md b/docs/dev/style.md index 44f0956c2..bb7a351f3 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md @@ -181,6 +181,30 @@ fn frobnicate(walrus: Option) { } ``` +# Early Returns + +Do use early returns + +```rust +// Good +fn foo() -> Option { + if !condition() { + return None; + } + + Some(...) +} + +// Not as good +fn foo() -> Option { + if condition() { + Some(...) + } else { + None + } +} +``` + # Getters & Setters If a field can have any value without breaking invariants, make the field public. @@ -189,7 +213,7 @@ Never provide setters. Getters should return borrowed data: -``` +```rust struct Person { // Invariant: never empty first_name: String, -- cgit v1.2.3 From fc3e591bdb28745ef29e90de2c1625e6d4e4a229 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Mon, 24 Aug 2020 12:49:36 +0200 Subject: Avoid monomorphization --- docs/dev/style.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'docs') diff --git a/docs/dev/style.md b/docs/dev/style.md index 44f0956c2..ae69cf1a7 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md @@ -231,6 +231,41 @@ if words.len() != 2 { } ``` +# 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*. +This allows for exceptionally good performance, but leads to increased compile times. +Runtime performance obeys 80%/20% rule -- only a small fraction of code is hot. +Compile time **does not** obey this rule -- all code has to be compiled. +For this reason, avoid making a lot of code type parametric, *especially* on the boundaries between crates. + +```rust +// Good +fn frbonicate(f: impl FnMut()) { + frobnicate_impl(&mut f) +} +fn frobnicate_impl(f: &mut dyn FnMut()) { + // lots of code +} + +// Not as good +fn frbonicate(f: impl FnMut()) { + // lots of code +} +``` + +Avoid `AsRef` polymorphism, it pays back only for widely used libraries: + +```rust +// Good +fn frbonicate(f: &Path) { +} + +// Not as good +fn frbonicate(f: impl AsRef) { +} +``` + # Documentation For `.md` and `.adoc` files, prefer a sentence-per-line format, don't wrap lines. -- cgit v1.2.3