string - 如何匹配表示为 OsStr 的文件扩展名?

标签 string rust

我正在尝试匹配一个文件扩展名:

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`

最佳答案

OsStrOsString存在正是因为文件名不是 UTF-8。 Rust 字符串文字是 UTF-8。这意味着您必须处理两种表示之间的转换。

一种解决方案是放弃 match 并使用 if-else 语句。参见 Stargateur's answer举个例子。

您还可以将扩展名转换为字符串。由于扩展名可能不是 UTF-8,这将返回另一个 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!"),
            }
        }
    };
}

如果您希望所有情况都使用空字符串作为回退,您可以这样做:

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 作为回退:

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,
        }
    });
}

关于string - 如何匹配表示为 OsStr 的文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42101070/

相关文章:

real-time - 我如何在 Rust 中进行实时编程?

rust - 我如何接受同一个 Serde 字段的多个反序列化名称?

java - 忽略?在 String ReplaceFirst 方法的正则表达式中

python - 弦乐变奏

swift - Swift 在使用 var 时是否有二次字符串连接?

java - 枚举到字符串的转换

c - 是否可以使用Rust中的指针访问结构的元素?

rust - 用特征别名替换特征绑定(bind)说 "the size for values cannot be known at compilation time"

rust - 如何使用 cargo 设置环境变量?

javascript - 大文本作为javascript函数中的参数