当我需要将借来的&str转换为String并将其存储到结构中时,变体str.to_owned()
和String::from(&str)
之间有区别吗?
示例:
#[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
}
}
// ...
}
这可以正常编译,因此这两种方法都可以使用。为什么通常首选变体1有一些内部差异或原因?