aboutsummaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-rw-r--r--docs/dev/style.md52
1 files changed, 52 insertions, 0 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md
index 397e85b35..bcd86fd3f 100644
--- a/docs/dev/style.md
+++ b/docs/dev/style.md
@@ -197,6 +197,43 @@ fn frobnicate(walrus: Option<Walrus>) {
197} 197}
198``` 198```
199 199
200Avoid preconditions that spawn function boundaries:
201
202
203```rust
204// Good
205fn string_literal_contents(s: &str) -> Option<&str> {
206 if s.starts_with('"') && s.ends_with('"') {
207 Some(&s[1..s.len() - 1])
208 } else {
209 None
210 }
211}
212
213fn foo() {
214 let s: &str = ...;
215 if let Some(contents) = string_literal_contents(s) {
216
217 }
218}
219
220// Not as good
221fn is_string_literal(s: &str) -> Option<&str> {
222 s.starts_with('"') && s.ends_with('"')
223 Some()
224}
225
226fn foo() {
227 let s: &str = ...;
228 if is_string_literal(s) {
229 let contents = &s[1..s.len() - 1];
230 }
231}
232```
233
234In the "Not as good" version, the precondition that `1` is a valid char boundary is checked in `is_string_literal` and utilized in `foo`.
235In the "Good" version, precondition check and usage are checked in the same block, and then encoded in the types.
236
200# Early Returns 237# Early Returns
201 238
202Do use early returns 239Do use early returns
@@ -271,6 +308,21 @@ if words.len() != 2 {
271} 308}
272``` 309```
273 310
311If allocation is inevitable, let the caller allocate the resource:
312
313```rust
314// Good
315fn frobnicate(s: String) {
316 ...
317}
318
319// Not as good
320fn frobnicate(s: &str) {
321 let s = s.to_string();
322 ...
323}
324```
325
274# Avoid Monomorphization 326# Avoid Monomorphization
275 327
276Rust 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*. 328Rust 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*.