rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Suggest replacing str::split with empty pattern with str::chars

Open Ravenslofty opened this issue 1 year ago • 1 comments

What it does

I was helping a friend learn Rust by going through Advent of Code 2020, and they needed to split a &str into a Vec<char>. They found the str::split method, and wrote string.split("").collect::<Vec<char>>(). While reviewing their code, this tripped me up a bit, since I would think of string.chars().collect::<Vec<char>>() instead. I think this would be a good candidate for a lint.

Advantage

  • I think this is more intuitive than splitting with an empty pattern

Drawbacks

  • as this playground shows, this is not a one-to-one replacement because str::split("") has leading and trailing empty strings.

Example

"hello world".split(""); 

The above should trigger a suggestion of replacing with

"hello world".chars();

Ravenslofty avatar Feb 18 '24 17:02 Ravenslofty

@rustbot claim

Vrajs16 avatar Apr 18 '24 02:04 Vrajs16