Skip to content

Commit 22b798d

Browse files
committedMay 17, 2024··
feat: rpt 35 - compile_error!()
1 parent 3bae11c commit 22b798d

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed
 

‎content/blog/rust-pro-tips-collection.md

+42-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: "Rust Pro Tips (collection)"
33
date: 2023-04-08
4-
lastmod: 2024-04-26
4+
lastmod: 2024-05-17
55
description: "Level up your Rust skills."
66
author: Jacob Lindahl
77
twitter: sudo_build
@@ -12,6 +12,47 @@ 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+
## 35. Force compilation failure
16+
17+
The `compile_error!(...)` macro forces compilation failure. This can be useful to indicate unsupported feature flag combinations or invalid macro arguments.
18+
19+
```rust
20+
compile_error!("Boo!");
21+
22+
fn main() {
23+
println!("Hello, world!");
24+
}
25+
```
26+
27+
Compiler output:
28+
29+
```txt
30+
Compiling playground v0.0.1 (/playground)
31+
error: Boo!
32+
--> src/main.rs:1:1
33+
|
34+
1 | compile_error!("Boo!");
35+
| ^^^^^^^^^^^^^^^^^^^^^^
36+
37+
error: could not compile `playground` (bin "playground") due to 1 previous error
38+
```
39+
40+
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0f32c3705ed84087f197e860087214cc) \
41+
[Docs](https://doc.rust-lang.org/std/macro.compile_error.html)
42+
43+
---
44+
45+
**Bonus tip #1**: Emit compiler _warnings_ using [`build.rs`](https://doc.rust-lang.org/cargo/reference/build-scripts.html):
46+
47+
```rust
48+
fn main() {
49+
#[cfg(feature = "funky-time")]
50+
println!("cargo::warning=Funky mode is enabled!");
51+
}
52+
```
53+
54+
**Bonus tip #2**: Emit structured diagnostics from proc macros using [the nightly `Diagnostic` API](https://doc.rust-lang.org/proc_macro/struct.Diagnostic.html). ([tracking issue #54140](https://github.com/rust-lang/rust/issues/54140))
55+
1556
## 34. Enable optional dependency features with a feature
1657

1758
[Tweet](https://twitter.com/sudo_build/status/1756269920126726455) [Toot](https://infosec.exchange/@hatchet/111906804455534802)

0 commit comments

Comments
 (0)
Please sign in to comment.