如何匹配表示为 OsStr 的文件扩展名? [英] How to match a file extension represented as an OsStr?
问题描述
我正在尝试针对文件扩展名match
:
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",
},
};
编译器说:
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`
推荐答案
OsStr
和 OsString
之所以存在,正是因为文件名不是 UTF-8.Rust 字符串文字是 UTF-8.这意味着您必须处理两种表示之间的转换.
OsStr
and OsString
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.
一种解决方案是放弃 match
并使用 if-else 语句.参见星际之门的回答示例.
One solution is to give up the match
and use if-else statements. See Stargateur's answer for an example.
您还可以将扩展名转换为字符串.由于扩展名可能不是 UTF-8,因此返回另一个 Option
:
You can also convert the extension to a string. Since the extension might not be UTF-8, this returns another Option
:
fn main() {
let file_path = std::path::Path::new("index.html");
let content_type = match file_path.extension() {
None => "",
Some(os_str) => {
match os_str.to_str() {
Some("html") => "text/html",
Some("css") => "text/css",
Some("js") => "application/javascript",
_ => panic!("You forgot to specify this case!"),
}
}
};
}
<小时>
如果您希望所有情况都使用空字符串作为后备,您可以执行以下操作:
If you want all cases to use an empty string as the fallback, you can do something like:
use std::ffi::OsStr;
fn main() {
let file_path = std::path::Path::new("index.html");
let content_type = match file_path.extension().and_then(OsStr::to_str) {
Some("html") => "text/html",
Some("css") => "text/css",
Some("js") => "application/javascript",
_ => "",
};
}
或者如果你想使用 None
作为后备:
Or if you want to use None
as the fallback:
use std::ffi::OsStr;
fn main() {
let file_path = std::path::Path::new("index.html");
let content_type = file_path.extension().and_then(OsStr::to_str).and_then(|ext| {
match ext {
"html" => Some("text/html"),
"css" => Some("text/css"),
"js" => Some("application/javascript"),
_ => None,
}
});
}
这篇关于如何匹配表示为 OsStr 的文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!