3

when I need to convert a borrowed &str to a String to store it into a struct, is there a difference between the variants str.to_owned() and String::from(&str)?

Example:

#[derive(Debug)]
pub struct LibraryEntry {
    pub title: String,
    book_path: String,
}

impl LibraryEntry {
    pub fn new(title: &str, book_path: &str) -> LibraryEntry {
        LibraryEntry {
            title: title.to_owned(),           // Variant 1
            book_path: String::from(book_path) // Variant 2
        }
    }

    // ...
}

This compiles fine, so both methods should work. Is there some internal difference or reason why variant 1 is usually preferred?

mcarton
  • 27,633
  • 5
  • 85
  • 95
LinusCDE
  • 141
  • 3
  • 8
  • 3
    Does this answer your question? [How to create a String directly?](https://stackoverflow.com/questions/31331356/how-to-create-a-string-directly) _"As of [Rust 1.9](https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-190-2016-05-26), `str::to_string`, `str::to_owned`, `String::from`, `str::into` all have the same performance characteristics. Use whichever you prefer."_ – Brian61354270 Jul 30 '20 at 13:25
  • 1
    Without knowing it properly my guess is that the owned just move the value mean while the from one it would copy the referenced str into a new String – Netwave Jul 30 '20 at 13:25
  • 1
    They're part of different traits (protocols) is about the only difference. `str::to_string` used to be less efficient but `str::to_owned` and `String::from` have always been pretty much optimal. Clippy used to recommend using `str::to_owned` when encountering an `str::to_string`, which might account for the relative popularity of the former. – Masklinn Jul 30 '20 at 13:55
  • Thanks for the feedback. So it seems that it doesn't really matter. Only personal taste and eventually some overhead with String::from(&str). Since the question refrenced by @Brian has some good anwser (which I simply didn't find), I'll remove this question as it's a possible duplicate. Or should I simply leave it, so the topic is easier to find for others? – LinusCDE Jul 30 '20 at 14:27
  • 1
    Don't delete your question. Indeed, duplicate questions help others find answers by providing many formulations for the same question/problem. – Francis Gagné Jul 30 '20 at 22:19

0 Answers0