Mutable References At Function Boundaries
Apply &mut references at function boundaries to edit data in place, showing that exclusive borrows end before new borrows begin.
Code
fn normalize(scores: &mut [i32]) {
// 独占借用:函数内可整体读写,调用结束后归还
for s in scores.iter_mut() {
if *s < 0 {
*s = 0;
}
}
}
fn bump_last(scores: &mut [i32], by: i32) {
if let Some(last) = scores.last_mut() {
*last += by;
}
}
fn main() {
let mut scores = vec![10, -3, 42, -7];
normalize(&mut scores);
println!("normalized: {:?}", scores);
bump_last(&mut scores, 8);
println!("bumped: {:?}", scores);
// 独占借用结束后即可再借:两次 &mut 不重叠
let first = &mut scores;
first[0] = 100;
println!("first edited: {:?}", first);
// 只读借用可与先前的 &mut 顺序共存,但不能同时
let peek: &[i32] = &scores;
println!("peek sum: {}", peek.iter().sum::<i32>());
}How it works
Mutable References At Function Boundaries reduces to the functions normalize, bump_last and main.
A single loop drives the file — for s in scores.iter_mut().
Points of care
- Runs with what the toolchain already gives you — nothing extra.
Using it
The primary signature is fn normalize(scores: &mut [i32])
The demo output is labeled (normalized:, bumped:, first edited:); each label names the call that printed it.
Execute the file and main walks through normalize and bump_last, in that order.
Key statements
fn bump_last(scores: &mut [i32], by: i32) {
if let Some(last) = scores.last_mut() {
*last += by;
}
}
fn normalize(scores: &mut [i32]) {
// 独占借用:函数内可整体读写,调用结束后归还
for s in scores.iter_mut() {
if *s < 0 {
*s = 0;
}
}
}
Interactive Tools for This Topic
FAQ
- What does Mutable References At Function Boundaries print when run?
- Run it as a complete program — the output lines carry labels such as `normalized:`, `bumped:`, `first edited:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.