Ref patterns, destructuring, and invisible borrows

Robert Grosse
Jan 17, 2018 · 5 min read
let opt = Some("Hello".to_string());match opt {
Some(_) => println!("We have a string"),
None => println!("We have None"),
}
match opt {
Some(mut s) => {
s.push_str(" world!");
println!("{}", s);
}
None => {}
}
let (a, (b, c)) = (1, (2, 4));
// a = 1, b = 2, c = 4
let temp = (1, (2, 4));
let a = temp.0;
let b = temp.1.0;
let c = temp.1.1;
struct Foo {
size: u32,
name: &'static str,
}
let Foo{size: a, name: b} = Foo{size: 42, name: "Bob"};
// a = 42, b = "Bob"
let &&&x = &&&42;
// x = 42
let &&y = &&&42;
// y = &42
let (x, &y) = (&32, &8);
// x = &32, y = 8
// What goes here ???
let &(???x, ???y) = &(4, 7);
let &(ref x, ref y) = &(4, 7);
let x       = &42;
let &ref y = &42;
// x = &42, y = &42
let ref z = 42;
// z = &42
match opt {
// opt is borrowed because of the ref pattern
// on the "left hand side" here
Some(ref s) => println!("We have a string"),
None => println!("We have None"),
}
match opt {
Some(_) => drop(opt),
None => println!("We have None"),
}

Robert Grosse

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade