I am trying to match
against a file extension:
let file_path = std::path::Path::new("index.html");
let content_type = match file_path.extension() {
None => "",
Some(os_str) => match os_str {
"html" => "text/html",
"css" => "text/css",
"js" => "application/javascript",
},
};
The compiler says:
error[E0308]: mismatched types
--> src/main.rs:6:13
|
6 | "html" => "text/html",
| ^^^^^^ expected struct `std::ffi::OsStr`, found str
|
= note: expected type `&std::ffi::OsStr`
found type `&'static str`
You could use
PartialEq<str>
trait forOsStr
.OsStr
andOsString
exist precisely because filenames are not UTF-8. A Rust string literal is UTF-8. That means you must deal with converting between the two representations.One solution is to give up the
match
and use if-else statements. See Stargateur's answer for an example.You can also convert the extension to a string. Since the extension might not be UTF-8, this returns another
Option
:If you want all cases to use an empty string as the fallback, you can do something like:
Or if you want to use
None
as the fallback: