Rust从入坑到入土-入坑-String compared to str

String compared to str

Rust String

Rust str

刚接触Rust时,可能我们对String和str之间的关系和区别不太清楚,以至于在编写函数时不太确定要用哪种类型比较好。本文主要就这个问题进行阐述。

Rust的官方文档在String的解释中,简要的指明了Stringstr之间的关系。

String

“The String type is the most common string type that has ownership over the contents of the string. It has a close relationship with its borrowed counterpart, the primitive str.”

str

“The str type, also called a ‘string slice’, is the most primitive string type. It is usually seen in its borrowed form, &str. It is also the type of string literals, &’static str.”

上述定义的阐述可以了解:string是最为通用的字符串类型,且对字符串值具有所有权。string和其借用str有着密切的联系。

str我们称之为str slicestr也是很最为原始的字符串类型。我们最常见到的是其借用形式:&str。str也用来标识字符串字面量:&’static str.

String是 dynamic heap 字符串类型,对字符串拥有所有权。而&str是一个不可变的存在于stack上的用来引用字符串的slice。


fn main(){

let mut contents = String::from("hello, world"); // 在栈创建了一个String类型的变量contents,其指向堆上的一个字符串

let first_word = find_first_word(&contents); // 在栈上c创建了一个&str类型的变量,指向contents所指向的字符串,ptr:0,len:1

println!("contents' first word is :{0}", first_word); // 预计输出 h

} // 回收contents所有权。first_word不具有所有权,不进行处理。

fn find_first_word(contents:&str)->&str{

&contents[0..1]

} // 无所有权,所以不对contents进行回收
本作品采用《CC 协议》,转载必须注明作者和本文链接
Wo-koo
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!