From 0bcec3760467995fb08e55ef6e7be697d13490a5 Mon Sep 17 00:00:00 2001 From: arferreira Date: Wed, 11 Feb 2026 20:37:45 -0500 Subject: [PATCH] Improve write! and writeln! error when called without destination --- library/core/src/macros/mod.rs | 6 ++++++ tests/ui/macros/write-missing-destination.rs | 7 +++++++ tests/ui/macros/write-missing-destination.stderr | 8 ++++++++ 3 files changed, 21 insertions(+) create mode 100644 tests/ui/macros/write-missing-destination.rs create mode 100644 tests/ui/macros/write-missing-destination.stderr diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 3176f3c06709..156ff846cbeb 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -611,6 +611,9 @@ macro_rules! write { ($dst:expr, $($arg:tt)*) => { $dst.write_fmt($crate::format_args!($($arg)*)) }; + ($($arg:tt)*) => { + compile_error!("requires a destination and format arguments, like `write!(dest, \"format string\", args...)`") + }; } /// Writes formatted data into a buffer, with a newline appended. @@ -649,6 +652,9 @@ macro_rules! writeln { ($dst:expr, $($arg:tt)*) => { $dst.write_fmt($crate::format_args_nl!($($arg)*)) }; + ($($arg:tt)*) => { + compile_error!("requires a destination and format arguments, like `writeln!(dest, \"format string\", args...)`") + }; } /// Indicates unreachable code. diff --git a/tests/ui/macros/write-missing-destination.rs b/tests/ui/macros/write-missing-destination.rs new file mode 100644 index 000000000000..02e0e096a907 --- /dev/null +++ b/tests/ui/macros/write-missing-destination.rs @@ -0,0 +1,7 @@ +// Check that `write!` without a destination gives a helpful error message. +// See https://github.com/rust-lang/rust/issues/152493 + +fn main() { + write!("S"); + //~^ ERROR requires a destination and format arguments +} diff --git a/tests/ui/macros/write-missing-destination.stderr b/tests/ui/macros/write-missing-destination.stderr new file mode 100644 index 000000000000..3136191ca17a --- /dev/null +++ b/tests/ui/macros/write-missing-destination.stderr @@ -0,0 +1,8 @@ +error: requires a destination and format arguments, like `write!(dest, "format string", args...)` + --> $DIR/write-missing-destination.rs:5:5 + | +LL | write!("S"); + | ^^^^^^^^^^^ + +error: aborting due to 1 previous error +