Skip to content

Commit af696ce

Browse files
authored
Merge pull request #258 from rylev/panic-macro-consistency
Add migration section for panic-macro-consistency
2 parents 4f90df3 + 7b96160 commit af696ce

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/rust-2021/panic-macro-consistency.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ println!(a); // Error: First argument must be a format string literal
3131
panic!(a); // Ok: The panic macro doesn't care
3232
```
3333

34-
(It even accepts non-strings such as `panic!(123)`, which is uncommon and rarely useful.)
34+
It even accepts non-strings such as `panic!(123)`, which is uncommon and rarely useful since it
35+
produces a surprisingly unhelpful message: `panicked at 'Box<Any>'`.
3536

3637
This will especially be a problem once
3738
[implicit format arguments](https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html)
@@ -56,4 +57,28 @@ panic!(a); // Error, must be a string literal
5657

5758
In addition, `core::panic!()` and `std::panic!()` will be identical in Rust 2021.
5859
Currently, there are some historical differences between those two,
59-
which can be noticable when switching `#![no_std]` on or off.
60+
which can be noticeable when switching `#![no_std]` on or off.
61+
62+
## Migration
63+
64+
A lint, `non_fmt_panics`, gets triggered whenever there is some call to `panic` that uses some
65+
deprecated behavior that will error in Rust 2021. The `non_fmt_panics` lint has already been a warning
66+
by default on all editions since the 1.50 release (with several enhancements made in later releases).
67+
If your code is already warning free, then it should already be ready to go for Rust 2021!
68+
69+
You can automatically migrate your code to be Rust 2021 Edition compatible or ensure it is already compatible by
70+
running:
71+
72+
```sh
73+
cargo fix --edition
74+
```
75+
76+
Should you choose or need to manually migrate, you'll need to update all panic invocations to either use the same
77+
formatting as `println` or use `std::panic::panic_any` to panic with non-string data.
78+
79+
For example, in the case of `panic!(MyStruct)`, you'll need to convert to using `std::panic::panic_any` (note
80+
that this is a function not a macro): `std::panic::panic_any(MyStruct)`.
81+
82+
In the case of panic messages that include curly braces but the wrong number of arguments (e.g., `panic!("Some curlies: {}")`),
83+
you can panic with the string literal by either using the same syntax as `println!` (i.e., `panic!("{}", "Some curlies: {}")`)
84+
or by escaping the curly braces (i.e., `panic!("Some curlies: {{}}")`).

0 commit comments

Comments
 (0)