Skip to content

Commit 5d0fcfb

Browse files
committed
modify str_to_string to be machine-applicable
1 parent e7efe43 commit 5d0fcfb

File tree

3 files changed

+18
-8
lines changed

3 files changed

+18
-8
lines changed

clippy_lints/src/strings.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -399,13 +399,17 @@ impl<'tcx> LateLintPass<'tcx> for StrToString {
399399
&& let ty::Ref(_, ty, ..) = ty.kind()
400400
&& ty.is_str()
401401
{
402-
span_lint_and_help(
402+
let mut applicability = Applicability::MachineApplicable;
403+
let snippet = snippet_with_applicability(cx, self_arg.span, "..", &mut applicability);
404+
405+
span_lint_and_sugg(
403406
cx,
404407
STR_TO_STRING,
405408
expr.span,
406409
"`to_string()` called on a `&str`",
407-
None,
408-
"consider using `.to_owned()`",
410+
"try",
411+
format!("{snippet}.to_owned()"),
412+
applicability,
409413
);
410414
}
411415
}

tests/ui/str_to_string.fixed

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#![warn(clippy::str_to_string)]
2+
3+
fn main() {
4+
let hello = "hello world".to_owned();
5+
//~^ ERROR: `to_string()` called on a `&str`
6+
let msg = &hello[..];
7+
msg.to_owned();
8+
//~^ ERROR: `to_string()` called on a `&str`
9+
}

tests/ui/str_to_string.stderr

+2-5
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,16 @@ error: `to_string()` called on a `&str`
22
--> tests/ui/str_to_string.rs:4:17
33
|
44
LL | let hello = "hello world".to_string();
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `"hello world".to_owned()`
66
|
7-
= help: consider using `.to_owned()`
87
= note: `-D clippy::str-to-string` implied by `-D warnings`
98
= help: to override `-D warnings` add `#[allow(clippy::str_to_string)]`
109

1110
error: `to_string()` called on a `&str`
1211
--> tests/ui/str_to_string.rs:7:5
1312
|
1413
LL | msg.to_string();
15-
| ^^^^^^^^^^^^^^^
16-
|
17-
= help: consider using `.to_owned()`
14+
| ^^^^^^^^^^^^^^^ help: try: `msg.to_owned()`
1815

1916
error: aborting due to 2 previous errors
2017

0 commit comments

Comments
 (0)