Skip to content

Commit a245552

Browse files
committed
rpt 38: debug_assert! macro
1 parent 82db05e commit a245552

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

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+
## 38. The `debug_assert!` macro
16+
17+
<!-- [Tweet]() [Toot]() -->
18+
19+
The `debug_assert!` macro creates an assertion only in debug builds. It is useful for confirming assumptions during development without risking performance degradation in the release build.
20+
21+
```rust
22+
impl Rectangle {
23+
pub fn new(width: u32, height: u32) -> Self {
24+
debug_assert!(
25+
u32::MAX / width >= height,
26+
"area calculation will overflow",
27+
);
28+
29+
Self { width, height }
30+
}
31+
32+
pub fn area(&self) -> u32 {
33+
self.width * self.height
34+
}
35+
}
36+
```
37+
38+
[Playground](https://play.rust-lang.org/?version=stable&mode=release&edition=2024&gist=c07b46949bdedf702cb4649b3504776c) <small>_Note: You can change the build mode using the dropdown next to the "Run" button._</small> \
39+
[Docs](https://doc.rust-lang.org/std/macro.debug_assert.html) \
40+
["Rust's Two Kinds of 'Assert' Make for Better Code"](https://tratt.net/laurie/blog/2023/rusts_two_kinds_of_assert_make_for_better_code.html) &mdash; Laurence Tratt
41+
1542
## 37. Block labels
1643

1744
[Tweet](https://twitter.com/sudo_build/status/1828719139797758422) [Toot](https://infosec.exchange/@hatchet/113038819765870560)

0 commit comments

Comments
 (0)