From 8f01adf6e751c5ae935b0b823c4060820cc28389 Mon Sep 17 00:00:00 2001 From: Andy Russell Date: Sat, 9 May 2026 23:47:09 -0400 Subject: [PATCH] suggest removing return type on use of void --- .../rustc_resolve/src/late/diagnostics.rs | 17 +++++++++++++++ tests/ui/suggestions/return-void.rs | 5 +++++ tests/ui/suggestions/return-void.stderr | 21 +++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 tests/ui/suggestions/return-void.rs create mode 100644 tests/ui/suggestions/return-void.stderr diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 6f86759d46c5f..93a9502461f4c 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -548,6 +548,23 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { && expected.starts_with("struct") { ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion) + } else if item_str.as_str() == "void" + && let Some((FnKind::Fn(.., fun), ..)) = self.diag_metadata.current_function + && let ast::FnRetTy::Ty(ty) = &fun.sig.decl.output + && ty.span == item_span + { + // check for accidental use of `void` as a return type + let return_ty_span = + self.r.tcx.sess.source_map().span_extend_to_prev_char(item_span, ')', true); + + ( + "functions with no return value use `()`".to_string(), + Some(( + return_ty_span, + "omit the return type to return `()` implicitly", + "".to_owned(), + )), + ) } else { // check if we are in situation of typo like `True` instead of `true`. let override_suggestion = diff --git a/tests/ui/suggestions/return-void.rs b/tests/ui/suggestions/return-void.rs new file mode 100644 index 0000000000000..542f3dede2bd2 --- /dev/null +++ b/tests/ui/suggestions/return-void.rs @@ -0,0 +1,5 @@ +#![crate_type = "lib"] + +pub fn foo() -> void {} //~ ERROR cannot find type `void` + +pub fn bar(v: void) {} //~ ERROR cannot find type `void` diff --git a/tests/ui/suggestions/return-void.stderr b/tests/ui/suggestions/return-void.stderr new file mode 100644 index 0000000000000..d488d9868b545 --- /dev/null +++ b/tests/ui/suggestions/return-void.stderr @@ -0,0 +1,21 @@ +error[E0425]: cannot find type `void` in this scope + --> $DIR/return-void.rs:3:17 + | +LL | pub fn foo() -> void {} + | ^^^^ functions with no return value use `()` + | +help: omit the return type to return `()` implicitly + | +LL - pub fn foo() -> void {} +LL + pub fn foo() {} + | + +error[E0425]: cannot find type `void` in this scope + --> $DIR/return-void.rs:5:15 + | +LL | pub fn bar(v: void) {} + | ^^^^ not found in this scope + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0425`.