as_deref_mut Rewrites Through An Option
Borrow a mutable inner value straight out of an Option with as_deref_mut, editing &str in place while None stays None.
Code
#[derive(Default, Debug)]
struct Profile {
nickname: Option<String>,
}
fn main() {
let mut profile = Profile { nickname: Some("old-nick".to_string()) };
// as_deref_mut:借到 &mut str,就地改写而不替换整个 String
if let Some(nick) = profile.nickname.as_deref_mut() {
nick.make_ascii_uppercase();
}
println!("upper: {:?}", profile.nickname);
// None 时保持 None,不会凭空创建默认值
let mut empty = Profile::default();
assert!(empty.nickname.as_deref_mut().is_none());
println!("none stays none: {:?}", empty.nickname);
}What the code does
The working surface is the function main — everything else is wiring.
Watch out for
- Ready as-is on a bare install of the language.
Applying it
Signature: fn main()
Running the file prints labeled results such as upper:, none stays none: — each operation’s effect is visible in the output.
Statements that matter
let mut profile = Profile { nickname: Some("old-nick".to_string()) };
if let Some(nick) = profile.nickname.as_deref_mut() {
nick.make_ascii_uppercase();
}
Interactive Tools for This Topic
FAQ
- What does as_deref_mut Rewrites Through An Option print when run?
- The script runs standalone; its 2 labeled outputs include `upper:`, `none stays none:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.