rust &str 的 into 和 to_string 和 to_owned 有什么区别?
在Rust中,&str是一个字符串切片类型,表示一个不可变的字符串引用。而into、to_string和to_owned是用于将&str转换为不同字符串类型的方法。
into:into方法是一个通用的转换方法,可以用于将&str转换为任何实现了From<&str>trait的类型。这意味着你可以将&str转换为String、Cow<str>(用于避免不必要的字符串拷贝)等类型。例如:
let s: &str = "hello";
let string: String = s.into();
let cow: Cow<str> = s.into();
to_string:to_string方法是&str类型的一个特定实现,用于将&str转换为String类型。这是因为String实现了From<&str>trait,所以可以使用into方法进行转换。因此,to_string与into方法在将&str转换为String时是等效的。例如:
let s: &str = "hello";
let string: String = s.to_string();
to_owned:to_owned方法是&str类型的另一个特定实现,用于将&str转换为String类型。与to_string方法不同的是,to_owned是一个方法而不是一个trait,它会创建一个新的String对象来存储&str的拷贝。例如:
let s: &str = "hello";
let string: String = s.to_owned();
总结来说,into方法是一个通用的转换方法,可以将&str转换为任何实现了From<&str> trait的类型。to_string和to_owned方法都是将&str转换为String类型的特定实现,但to_string是通过into方法进行转换的一种语法糖。
原文地址: http://www.cveoy.top/t/topic/ja7n 著作权归作者所有。请勿转载和采集!