Is there ever a case you'd want to use &String::new() for something expecting &str?

57 points yoav-lavi

In a previous PR to clippy, an suggestion from the maintainers (@flip1995) came up to create a lint detecting passing an owned string to something expecting where "" would be accepted. I want to follow up on this and open an issue (and perhaps a PR) to implement this, but first I want to make sure I'm not missing anything.

There's the case that something is typed &String which doesn't allow for "", but otherwise if something is expecting &str, is there any reason to ever use &String::new()?

When checking godbolt.org it seems that &String::new() does an extra allocation although in benchmarks they seemed to perform similarly (which leads me to believe it may be optimized away in some cases, or that the allocation is almost insignificant in this case).

See examples of this happening here (might include cases of &String)

Thank you!

Edit: opened the issue, please still comment here (or on the issue) if there are cases where this check would not be valid, thanks!

Edit 2: Apparently String::new() should not cause an allocation:

Given that the String is empty, this will not allocate any initial buffer.