如何匹配表示为 OsStr 的文件扩展名? [英] How to match a file extension represented as an OsStr?

查看:76
本文介绍了如何匹配表示为 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`

推荐答案

OsStrOsString 之所以存在,正是因为文件名不是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆