面试题答案
一键面试1. 借用规则说明
在Rust中,借用规则主要有以下几点:
- 同一时间内,要么只能有一个可变引用(mutable reference),要么只能有多个不可变引用(immutable references)。
- 引用的生命周期必须足够长,要长于使用它的代码块。
对于统计字符串中特定字符出现次数的函数,我们可以使用不可变借用,因为我们不需要修改字符串内容。
2. 代码实现
fn count_char(s: &str, target: char) -> u32 {
let mut count = 0;
for c in s.chars() {
if c == target {
count += 1;
}
}
count
}
3. 调用示例
fn main() {
let s = "hello world";
let target = 'l';
let result = count_char(s, target);
println!("The character '{}' appears {} times in '{}'", target, result, s);
}
在上述代码中,count_char
函数接收一个字符串切片 &str
的不可变引用 s
和目标字符 target
。函数内部通过 chars
方法遍历字符串中的每一个字符,并与目标字符进行比较,统计出现次数。整个过程只涉及不可变借用,遵循了Rust的借用规则,不会出现生命周期错误。