Pre-RFC: Add FromStr to the prelude

I would like to propose adding the FromStr trait to the prelude

Motivation

The FromStr trait is commonly used as an idiomatic way to parse strings into certain types. It is so common that there are over 200 thousand rust files on GitHub containing std::str::FromStr (and about 70 instances of its usage on the rust-lang/rust). The search also takes into account comments and documentation, which don't make much difference.

As a Rust developer, sometimes I also prefer using the T::from_str(v) syntax in situations where I'd like to move the type to the left instead of examining the entire processing chain. However, today this approach is penalized by the need to import FromStr, which is too lengthy for short use-cases.

with parse

let i = v.method().other_method().and_another_one().parse::<usize>();

with from_str today

use std::str::FromStr;
let j = usize::from_str(v.method().other_method().and_another_one());

with from_str after this pre-RFC

let j = usize::from_str(v.method().other_method().and_another_one());

Adding FromStr to the prelude simplifies the code by eliminating imports and making this syntax easier to use.

Drawbacks

  • Expands the prelude without adding any functionality.

Related

3 Likes

I have a quibble here: these results include results from forks (trying to select "not forks" in the advanced search just removes the term…and still returns results from forks). Given that there are 11.8k forks of rust-lang/rust (and some fork results are on the first page), it certainly isn't this many. I also see impl std::str::FromStr which, presumably, doesn't care that much as it's already committed to 5 lines for the impl.

Sure, the search results on GitHub may not be the most reliable statistics, but it's the only one I know of, except perhaps for the 5000 crates analysis which had 856 FromStr imports, which is quite a lot in my opinion.

Although it is unclear to me whether it includes unchanged forks. As far as I know it doesn't.

edit: fixed link

In my opinion, the FromStr crate belongs to the same category as FromIterator, which was added to the 2021 edition prelude, and the key point is that it is common enough to be handled in the same way.

This is more compelling to me as it also puts it in context as to how much 856 is in comparison to other imports. Thanks.

2 Likes

In a new edition, I wish FromStr took a lifetime for its &str argument so it could be used for zero copy parsing

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.