Skip to content

Commit e315fd9

Browse files
bors[bot]matklad
andauthored
Merge #6090
6090: More style advice r=matklad a=matklad bors r+\n🤖 Co-authored-by: Aleksey Kladov <[email protected]>
2 parents bdc1f76 + b069c1c commit e315fd9

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

docs/dev/style.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,43 @@ fn frobnicate(walrus: Option<Walrus>) {
197197
}
198198
```
199199

200+
Avoid preconditions that spawn function boundaries:
201+
202+
203+
```rust
204+
// Good
205+
fn 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+
213+
fn foo() {
214+
let s: &str = ...;
215+
if let Some(contents) = string_literal_contents(s) {
216+
217+
}
218+
}
219+
220+
// Not as good
221+
fn is_string_literal(s: &str) -> Option<&str> {
222+
s.starts_with('"') && s.ends_with('"')
223+
Some()
224+
}
225+
226+
fn foo() {
227+
let s: &str = ...;
228+
if is_string_literal(s) {
229+
let contents = &s[1..s.len() - 1];
230+
}
231+
}
232+
```
233+
234+
In the "Not as good" version, the precondition that `1` is a valid char boundary is checked in `is_string_literal` and utilized in `foo`.
235+
In the "Good" version, precondition check and usage are checked in the same block, and then encoded in the types.
236+
200237
# Early Returns
201238

202239
Do use early returns
@@ -271,6 +308,21 @@ if words.len() != 2 {
271308
}
272309
```
273310

311+
If allocation is inevitable, let the caller allocate the resource:
312+
313+
```rust
314+
// Good
315+
fn frobnicate(s: String) {
316+
...
317+
}
318+
319+
// Not as good
320+
fn frobnicate(s: &str) {
321+
let s = s.to_string();
322+
...
323+
}
324+
```
325+
274326
# Avoid Monomorphization
275327

276328
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*.

0 commit comments

Comments
 (0)