Rust difference between str.to_owned() and String::from(&str)

Viewed 185

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?

0 Answers
Related