Noob to rust, is there a reason to use if / if let over match statements or is it just a style preference?
if let Pattern(binding) = thing { ... } else { ... }
has been available for a long time. What was recently stabilized is let Pattern(binding) = thing else { ... };
which is syntax sugar for let binding = if let Pattern(binding) { binding } else { ... };
And facilitates easier unwrapping in early exit or default scenarios, without an extra level of indentation.However, while style truly is subjective, I'm not sure anyone could convince me that
match foo {
true => println!("hello"),
_ => {}
}
is the same or better than if foo {
println!("hello");
}
The RFC for "if let" has some good motivating examples as well https://rust-lang.github.io/rfcs/0160-if-let.html``` if cx.path == "/tags" { return tags::serve_list(cx).await; } else if cx.path.starts_with("/tags/") { return tags::serve_single(cx).await; }
if cx.path == "/settings" {
return settings::serve(cx).await;
}
if cx.path == "/search" {
return search::serve(cx).await;
}
if cx.path == "/login" {
return login::serve_login(cx).await;
}
if cx.path == "/patreon/oauth" {
return login::serve_patreon_oauth(cx).await;
}
if cx.path == "/logout" {
return login::serve_logout(cx).await;
}
if cx.path == "/debug-credentials" {
return login::serve_debug_credentials(cx).await;
}
if cx.path == "/comments" {
return comments::serve(cx).await;
}
if cx.path == "/latest-video" {
return latest_video::serve(cx).await;
}
if cx.path == "/patron-list" {
return patron_list::serve(cx).await;
}
if cx.path == "/index.xml" {
return cx
.serve_template("index.xml", Default::default(), mime::atom())
.await;
}
```I would probably write that with a match, personally. I didn't say match was useless, just that if and if let pull their weight as features, in my opinion, even though you could express them as a match if you really wanted to.
I could've sworn at some point some paths had something slightly more involved (strip slashes, some starts_with or trim_prefix, etc.) but the snippet as you've copied it is certainly... not great.