Reputation: 295
I have:
if std::env::consts::OS == "macos" {
// Do something
} else if std::env::consts::OS == "linux" {
// Do the same thing
}
Is there a way I could check for both of these in one line?
Upvotes: 0
Views: 2108
Reputation: 169256
You could use the logical "or" operator ||
:
if std::env::consts::OS == "macos" || std::env::consts::OS == "linux" {
// Do something
}
Or match
, which is a tad more terse in expressing what you want to match, but requires you to cover all possibilities, so a catch-all pattern is required even if you don't want to do anything in that case:
match std::env::consts::OS {
"macos" | "linux" => {
// Do something.
},
_ => {
// No other match arms matched, maybe do something, or don't.
},
};
As a side note, testing what platform you are on is usually a last resort when no other kind of detection will work. It's better to test what capabilities you have than to ask what platform you are on, for two reasons: first, that's the actual question you want to answer, and second, maybe the platforms that don't have that capability right now will sometime later.
Upvotes: 4