Closed
Description
"Use" in patterns would introduce a new feature and fix a small pain point in current Rust.
Currently this doesn't work:
fn main() {
let x = 1;
let y = 2;
match x {
y => println!("{} {}", x, y),
z => println!("{} {} {}", x, y, z)
}
}
I propose "use" in patterns so that it can be made to work:
fn main() {
let x = 1;
let y = 2;
match x {
use y => println!("{} {}", x, y),
z => println!("{} {} {}", x, y, z)
}
}
"use" in patterns should take an expression, no reason to accept only variables if you can just put the result of any expression in a variable.
This can also be combined with destructuring:
fn main() {
let x = Some(1);
let y = 2;
match x {
Some(use y) => println!("{} {}", x, y),
Some(z) => println!("{} {} {}", x, y, z),
None => {}
}
}
Another effect of "use" in patterns can be summarized in "WHY'S RUST CONTEXT-SENSITIVE?!". Check out the following code (assume the author is using #[allow(non_snake_case)]
):
const SOMETHING: u32 = 2; // (un)comment to break
let x = 1;
let v = 0;
match x {
SOMETHING if v < 10 => println!("<10 {} {}", x, SOMETHING),
SOMETHING if v < 5 => println!("<5 {} {}", x, SOMETHING),
_ => println!("{}", x),
}
use
in patterns also lets you use ranges in patterns:
let x: (Option<RangeFull>,) = (Some(..),);
match x {
(Some(use ..),) => println!("got rangefull"),
_ => println!("no rangefull")
}