When should I use String vs &str?

submited by
Style Pass
2024-10-16 18:30:03

Rust has two main string types: String and &str. Sometimes, people argue that these two types make Rust code difficult to write, because you have to think about which one you should be using in a given situation. My experience of writing Rust is that I don’t really think about this very much, and this post is about some rules of thumb that you can use to be like me.

We’re now doing much less copying. We do need to add a & on to String values that we wish to pass into first_word, but that’s not too bad, the compiler will help us when we forget:

Following this rule will get you through 95% of situations successfully. Yes, that number was found via the very scientific process of “I made it up, but it feels correct after writing Rust for the last twelve years.”

Always use String in structs, and for functions, use &str for parameters. If the return type of your function is derived from an argument and isn’t mutated by the body, return &str. If you run into any trouble here, return String instead.

Leave a Comment