Let Chains Combine Pattern Conditions
Since Rust 1.88 let chains join if-let bindings with boolean checks in one condition, so earlier bindings feed later patterns without nesting.
Code
fn lookup<'a>(env: &[(&'a str, &'a str)], key: &str) -> Option<&'a str> {
for &(key_env, value) in env {
if key_env == key {
return Some(value);
}
}
None
}
fn main() {
let config = [("host", "db.internal"), ("port", "5432")];
let empty_host = [("host", ""), ("port", "5432")];
let missing_port = [("host", "db.internal")];
// let 链(Rust 1.88 起稳定,需要 edition 2024):
// 同一个 if 条件里串联模式绑定与布尔判断,前面的绑定参与后面的条件
if let Some(host) = lookup(&config, "host")
&& !host.is_empty()
&& let Some(port) = lookup(&config, "port")
{
println!("dial {host}:{port}");
} else {
println!("config incomplete");
}
// host 是空串:第二个条件失败,整条链落到 else
if let Some(host) = lookup(&empty_host, "host")
&& !host.is_empty()
&& let Some(port) = lookup(&empty_host, "port")
{
println!("dial {host}:{port}");
} else {
println!("config incomplete");
}
// port 缺失:第三个条件失败
if let Some(host) = lookup(&missing_port, "host")
&& !host.is_empty()
&& let Some(port) = lookup(&missing_port, "port")
{
println!("dial {host}:{port}");
} else {
println!("config incomplete");
}
}How the snippet works
Everything happens inside the functions lookup and main.
The one repetition in this snippet is the loop for &(key_env, value) in env.
Applying it
Running the file prints labeled results such as dial, config incomplete — each operation’s effect is visible in the output.
The entry point wires lookup together — run it once and the whole demo flows.
Statements that matter
return Some(value);
if let Some(host) = lookup(&missing_port, "host")
&& !host.is_empty()
&& let Some(port) = lookup(&missing_port, "port")
{
println!("dial {host}:{port}");
} else {
println!("config incomplete");
}
if let Some(host) = lookup(&empty_host, "host")
&& !host.is_empty()
&& let Some(port) = lookup(&empty_host, "port")
{
println!("dial {host}:{port}");
} else {
println!("config incomplete");
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Let Chains Combine Pattern Conditions print when run?
- No setup needed: run the file and look for labeled lines like `dial`, `config incomplete` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.