rust-clippy/tests/ui/format.rs

97 lines
2.6 KiB
Rust
Raw Normal View History

2019-02-24 05:30:08 +00:00
// run-rustfix
#![allow(
2022-07-25 20:36:03 +00:00
unused_tuple_struct_fields,
clippy::print_literal,
clippy::redundant_clone,
clippy::to_string_in_format_args,
clippy::needless_borrow
)]
2018-07-28 15:34:52 +00:00
#![warn(clippy::useless_format)]
struct Foo(pub String);
macro_rules! foo {
2019-03-10 17:19:47 +00:00
($($t:tt)*) => (Foo(format!($($t)*)))
}
fn main() {
2017-02-08 13:58:07 +00:00
format!("foo");
format!("{{}}");
format!("{{}} abc {{}}");
format!(
r##"foo {{}}
" bar"##
);
let _ = format!("");
2017-02-08 13:58:07 +00:00
format!("{}", "foo");
2019-01-31 01:15:29 +00:00
format!("{:?}", "foo"); // Don't warn about `Debug`.
format!("{:8}", "foo");
format!("{:width$}", "foo", width = 8);
2019-01-31 01:15:29 +00:00
format!("{:+}", "foo"); // Warn when the format makes no difference.
format!("{:<}", "foo"); // Warn when the format makes no difference.
format!("foo {}", "bar");
format!("{} bar", "foo");
let arg = String::new();
2017-02-08 13:58:07 +00:00
format!("{}", arg);
2019-01-31 01:15:29 +00:00
format!("{:?}", arg); // Don't warn about debug.
format!("{:8}", arg);
format!("{:width$}", arg, width = 8);
2019-01-31 01:15:29 +00:00
format!("{:+}", arg); // Warn when the format makes no difference.
format!("{:<}", arg); // Warn when the format makes no difference.
format!("foo {}", arg);
format!("{} bar", arg);
2019-01-31 01:15:29 +00:00
// We dont want to warn for non-string args; see issue #697.
format!("{}", 42);
format!("{:?}", 42);
format!("{:+}", 42);
format!("foo {}", 42);
2016-02-20 20:15:05 +00:00
format!("{} bar", 42);
2019-01-31 01:15:29 +00:00
// We only want to warn about `format!` itself.
println!("foo");
println!("{}", "foo");
println!("foo {}", "foo");
println!("{}", 42);
println!("foo {}", 42);
2019-01-31 01:15:29 +00:00
// A `format!` inside a macro should not trigger a warning.
foo!("should not warn");
2019-01-31 01:15:29 +00:00
// Precision on string means slicing without panicking on size.
2019-03-10 17:19:47 +00:00
format!("{:.1}", "foo"); // Could be `"foo"[..1]`
format!("{:.10}", "foo"); // Could not be `"foo"[..10]`
format!("{:.prec$}", "foo", prec = 1);
format!("{:.prec$}", "foo", prec = 10);
format!("{}", 42.to_string());
let x = std::path::PathBuf::from("/bar/foo/qux");
format!("{}", x.display().to_string());
2019-08-23 08:46:23 +00:00
// False positive
let a = "foo".to_string();
let _ = Some(format!("{}", a + "bar"));
// Wrap it with braces
let v: Vec<String> = vec!["foo".to_string(), "bar".to_string()];
let _s: String = format!("{}", &*v.join("\n"));
format!("prepend {:+}", "s");
// Issue #8290
let x = "foo";
let _ = format!("{x}");
let _ = format!("{x:?}"); // Don't lint on debug
let _ = format!("{y}", y = x);
// Issue #9234
let abc = "abc";
let _ = format!("{abc}");
let xx = "xx";
let _ = format!("{xx}");
}