Reborrowing Instead Of Moving Ownership
Passing &mut to a function is an implicit reborrow: the borrow returns when the call ends, and &mut *value narrows the type without transferring.
Code
fn append_suffix(buf: &mut String) {
buf.push_str("-draft");
}
fn clear(buf: &mut String) {
buf.clear();
}
fn main() {
let mut title = String::from("report");
// 传 &mut 是隐式 reborrow:调用结束借用立即归还,
// 同一个变量可以反复可变借用,所有权没有转移
append_suffix(&mut title);
println!("after first: {title}");
append_suffix(&mut title);
println!("after second: {title}");
// 显式 reborrow:&mut *title 把 &mut String 缩窄成 &mut str
let view: &mut str = &mut *title;
view.make_ascii_uppercase();
println!("upper: {title}");
clear(&mut title);
println!("len after clear: {}", title.len());
}How the snippet works
Reborrowing Instead Of Moving Ownership keeps everything in the functions append_suffix, clear and main.
Using it
Entry signature: fn append_suffix(buf: &mut String)
Running the file prints labeled results such as after first:, after second:, upper: — each operation’s effect is visible in the output.
The entry point wires append_suffix and clear together — run it once and the whole demo flows.
Key statements
fn append_suffix(buf: &mut String) {
buf.push_str("-draft");
}
fn clear(buf: &mut String) {
buf.clear();
}
Interactive Tools for This Topic
FAQ
- What does Reborrowing Instead Of Moving Ownership print when run?
- Invoke the file as-is — the `after first:`, `after second:`, `upper:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.