Prefer explicit generic when parsing?

I'm new to rust. Skimming the book/style/docs I stumbled upon this:

The Styleguide asks me to use type annotations for clarification; prefer explicit generics when inference fails whereas the book tells me to

let guess: u32 = "42".parse().expect("Not a number!");

So why is this example not

let guess = "42".parse::<u32>().expect("Not a number!");


Take a look at the url of the first thing you linked. It's a very very old document from the very first stable release of Rust.

I would say that at this time, both are considered idiomatic.

1 Like

Both syntaxes are equally valid. The first says that guess is a u32 and lets inference figure out which type, T, to use in the str::parse() method, while the second tells the compiler that we're using u32 with str::parse() and it then has enough information to infer guess is a u32.

I personally find let guess: u32 = ... to be cleaner than using turbofish (parse::<u32>()) to tell the compiler which type to use. The extra angle brackets and :: can sometimes add unnecessary visual noise, which is distracting and may confuse people who are less familiar with Rust.

1 Like

I don't even remember how I ended up with this URL :slight_smile: is there a newer styleguide?

You probably got it from google. They really like giving people old Rust documentation.

To the best of my knowledge there isn't an official style guide, per-se. Conventions and best practices evolve over time, so I'm guessing they chose to step back and wait for these things to emerge organically. Maintaining a style guide is also a lot of work and the Rust project has finite resources.

The closest is probably The API Guidelines, but that focuses more on how to design your code and write packages, not the nitty-gritty details of what syntax to use.


Running your code through clippy will also give you some pointers on good style and idiomatic code.

It's changed a lot since it was actually a style guide, but I believe the current document is this "Rust Style Guide" and related markdown files in the fmt-rfcs repository. Everywhere that used to host the style guide links back here - though this current "Rust Style Guide" does not actually document any style outside of formatting guidelines. It makes no comment on explicit generics vs. implicit.

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