因为这些类型可以被强制转换,所以如果我们使用这些类型,函数将接受更少的类型:
1- 对字符串的引用可以被强制转换为字符串切片。例如创建一个函数:
fn count_wovels(words:&String)->usize{
let wovels_count=words.chars().into_iter().filter(|x|(*x=='a') | (*x=='e')| (*x=='i')| (*x=='o')|(*x=='u')).count();
wovels_count
}
如果你传递&str
,它将不会被接受:
let name="yilmaz".to_string();
println!("{}",count_wovels(&name));
但是如果该函数接受 &str
作为参数
// words:&str
fn count_wovels(words:&str)->usize{ ... }
我们可以将这两种类型都传递给函数
let name="yilmaz".to_string();
println!("{}",count_wovels(&name));
println!("{}",wovels("yilmaz"))
通过这样,我们的函数可以接受更多类型
2- 同样地,对于 Box 的引用 &Box[T]
,将被强制转换为 Box 内部值的引用 Box[&T]
。例如
fn length(name:&Box<&str>){
println!("lenght {}",name.len())
}
这个只接受 &Box<&str>
类型
let boxed_str=Box::new("Hello");
length(&boxed_str);
如果我们将&str
作为类型传递,就可以同时传递这两种类型
3- 引用Vec和数组之间也存在类似的关系
fn square(nums:&Vec<i32>){
for num in nums{
println!("square of {} is {}",num,num*num)
}
}
fn main(){
let nums=vec![1,2,3,4,5];
let nums_array=[1,2,3,4,5];
square(&nums);
}
这适用于两种类型
fn square(nums:&[i32]){..}
&str
更普遍(即:不限制使用范围)而且没有降低功能”。另外,我认为第三点通常并不那么重要。通常Vec
和String
会在栈上存储,甚至会在当前的栈框架附近存储。栈通常是热的,并且解引用将从CPU缓存中提供服务。 - Lukas Kalbertodttotal_price(&prices[0..4])
不需要为切片分配新的向量。 - Matthieu M.&str
以及为什么要这样做(因为我以前学的是Python,通常不需要明确处理类型)。这个回答完美地解决了我的困惑。 - C.Nivs&String
或&Vec
上的&self
方法(即capacity
)时,接受&String
或&Vec
才有意义。此外,所有这些内容都不适用于可变借用,即&mut Vec
或&mut String
,当您想要增加或缩小集合时,这些是合法需要的。 - Arnavion