因为这些类型可以被强制,所以如果我们使用这些类型,函数将接受更少的类型:
1- String的引用可以被强制转换为str切片。例如,创建一个函数:
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));
// this is not allowed because argument should be &String but we are passing str
// println!("{}",wovels("yilmaz"))
但如果该函数接受&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);
// expected reference `&Box<&str>` found reference `&'static str`
// length("hello")
如果将&str作为类型传递,则可以同时传递两个类型
Vec的ref和数组的ref之间存在类似的关系
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];
// only &Vec<i32> is accepted
square(&nums);
// mismatched types: mismatched types expected reference `&Vec<i32>` found reference `&[{integer}; 5]`
//square(&nums_array)
}
这对两种类型都适用
fn square(nums:&[i32]){..}