The Ultimate Guide to Rust Newtypes

Hi all :wave: I'm a huge fan of type-driven design. It's the most effective way I know to reduce human error, clarify the flow of errors through programs, and keep my tests sanely structured.

I enjoy it so much, that I put together a comprehensive guide combinging everything I know about it: The Ultimate Guide to Rust Newtypes!

If you have examples of effective uses of newtypes from your own work, or you can think of some aspect of newtyping that I've forgotten to include, please let me know! I'd love to hear about it.

7 Likes

First of all, thanks for the article! It's great to have guides like this one that summarize a subject :slight_smile:.

One thing that I differ from what's being said is that about FromStr. It's true that it predates the implementation of TryInto and that for the most part it's similar to TryFrom<&str>, but those differences are precisely the reason why one should be used over the other.

Specifically for Newtypes that wrap around String, I recommend the use of FromStr rather than TryFrom<&str>. You get nice things with it such as the parse method on str:

let title = "Can't touch this".parse()?;

It's a nice reminder that we are parsing a string, not just a type conversion.

And there's also the DeserializeFromStr derive macro from serde_with, so that the deserialization takes care of the parsing.

2 Likes

Wow. In all my time writing Rust, str::parse went completely over my head! Rust never disappoints in the number of ways there are to accomplish something :joy:

Thank you for this comment - I've learned something! I'll update the guide to take these points into account.

2 Likes

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.