[Conversion Traits] FromStr vs From<&str> vs Display vs

Hi I want to ask something about common conversion traits which I find helpful but little confusing in Rust

Mainly it's about FromStr vs From<String> vs Display, etc. as converting from/to String is quite common

  1. what's difference between TryFrom<&str>and FromStr? which one should I impl for my custom type ?

  2. By impl From<String>, I automatically have Into<String>, this is good.
    But by impl Display, I also have a to_string() method whose name also suggests a conversion into String, which one should I use?

  3. I have seen many librarys impl raw methods like into_str, into_string, into_u8 as conversion method, which ignores all above utility. Is this simply history reason and we should try not doing so?

There are many other scenarios which make me confusing

Generally, if all these looking-similiar traits should manually be impled identically, why does rust have them each?

Or if they have difference semantics and use cases, what's that and why does they have seemingly un-distinguishable method name ?

Thanks in advance!

1 Like

You should prefer FromStr to TryFrom<&str>. The difference isn't large, but FromStr existed before TryFrom. Methods such as str::parse use the FromStr trait.

The From<String> trait gives the conversion String → YourStruct, whereas Display gives YourStruct → String. They are not comparable because they do different things, so you should use the one that does what you want.

As for raw into_string method versus to_string from Display, the into and to prefixes are used in different contexts. See naming in the API guidelines. If you have an into_string method, you should probably also implement Into<String>, but having a method with string explicitly in the name can be good for making code more readable.


Code should usually* be using into, parse, try_into when your dealing with different forms of the same data. Anything further away such as extracting or processing is better served by some other named function. to_string/Display being an example as it is for user-facing output rather than all the data in a different form.

*A custom error might use into from a source error and I'm not sure I would class the new error as being a different form.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.