面试题答案
一键面试不可变借用规则
- 规则:
- 可以有多个不可变借用同时存在。
- 不可变借用期间,不能有可变借用(包括对同一数据的可变借用以及对借用数据内部可修改部分的可变借用等情况)。
- 应用场景:
- 当需要在多个地方读取数据而不修改它时,使用不可变借用。例如,在一个函数中统计字符串中某个字符出现的次数,只需要读取字符串内容:
fn count_char(s: &str, c: char) -> u32 {
s.chars().filter(|&ch| ch == c).count() as u32
}
fn main() {
let s = "hello world";
let count = count_char(&s, 'l');
println!("The character 'l' appears {} times.", count);
}
- 违反规则导致的编译错误:如果在不可变借用存在时尝试进行可变借用,编译器会报错。例如:
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s; // 报错:不能在不可变借用 `r1` 存在时进行可变借用
println!("{}", r1);
println!("{}", r2);
}
编译时会提示类似 cannot borrow
s as mutable because it is also borrowed as immutable
的错误信息。
可变借用规则
- 规则:
- 同一时间只能有一个可变借用。
- 可变借用期间,不能有不可变借用(包括对同一数据的不可变借用以及对借用数据内部可读取部分的不可变借用等情况)。
- 应用场景:
- 当需要修改数据时,使用可变借用。比如向一个可变的字符串中追加内容:
fn append_to_string(s: &mut String, append_str: &str) {
s.push_str(append_str);
}
fn main() {
let mut s = String::from("hello");
append_to_string(&mut s, " world");
println!("{}", s);
}
- 违反规则导致的编译错误:如果在可变借用存在时尝试进行不可变借用,或者有多个可变借用同时存在,编译器会报错。例如:
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s; // 报错:不能有多个可变借用同时存在
let r3 = &s; // 报错:不能在可变借用 `r1` 存在时进行不可变借用
println!("{}", r1);
println!("{}", r2);
println!("{}", r3);
}
编译时会提示类似 cannot borrow
s as mutable more than once at a time
(针对多个可变借用的情况) 或 cannot borrow
s as immutable because it is also borrowed as mutable
(针对在可变借用时尝试不可变借用的情况)的错误信息。