Skip to content

Commit 6a2d3af

Browse files
committed
rpt 37: block labels
1 parent 6758927 commit 6a2d3af

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: content/blog/rust-pro-tips-collection.md

+27
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,33 @@ license:
1212

1313
This is a collection of Rust "pro tips" that I've collected, most of which have been [posted on Twitter](https://twitter.com/search?q=%23RustProTip%20%40sudo_build&src=typed_query&f=top). I'll keep updating this post as I write more. Tips are ordered in reverse chronological order, with the most recent ones at the top.
1414

15+
## 37. Block labels
16+
17+
<!-- [Tweet]() [Toot]() -->
18+
19+
Implicit returns from blocks aren't always flexible enough to describe the desired logic. Separate functions aside, the problem can be resolved inline by introducing a block label.
20+
21+
```rust
22+
let my_nonzero_u24: Option<u32> = 'extract: {
23+
if buf.len() < 3 {
24+
break 'extract None;
25+
}
26+
let mut bytes = [0u8; 4];
27+
bytes[1..].copy_from_slice(&buf[..3]);
28+
let value = u32::from_be_bytes(bytes);
29+
if value == 0 {
30+
None
31+
} else {
32+
Some(value)
33+
}
34+
};
35+
```
36+
37+
Note: [Loops can also be annotated with labels](https://doc.rust-lang.org/rust-by-example/flow_control/loop/nested.html).
38+
39+
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bf444f24278e7801f1b845709065dbdf) \
40+
[RFC #2046](https://rust-lang.github.io/rfcs/2046-label-break-value.html)
41+
1542
## 36. Specify the type of `self` in method signatures
1643

1744
[Tweet](https://x.com/sudo_build/status/1813491727174709278) [Toot](https://infosec.exchange/@hatchet/112800895144267784)

0 commit comments

Comments
 (0)