You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rust中如何获取路径的驱动器盘符字符串?

从Windows路径的PrefixComponent中提取raw前缀字符串 "D:"

你可以通过模式匹配识别Component::Prefix类型的组件,再调用PrefixComponent的as_os_str()方法获取其raw值,最后转换为字符串即可。

修改后的代码如下:

use std::path::{Path, Component, PrefixComponent};

fn main() {
    let filepath = "D:\\Household\\Internet\\September_2022_Statement.pdf";
    let path = Path::new(filepath);
    
    for component in path.components() {
        if let Component::Prefix(prefix) = component {
            // Windows路径前缀为合法UTF-8,可安全转换为&str
            if let Some(raw_prefix) = prefix.as_os_str().to_str() {
                println!("提取到的raw前缀: {}", raw_prefix);
            }
        }
    }
}

代码说明

  1. 遍历路径组件时,用if let模式匹配筛选出Component::Prefix类型项,获取内部的PrefixComponent实例。
  2. PrefixComponent::as_os_str()直接返回对应输出里的raw值(OsStr类型)。
  3. 调用to_str()将OsStr转换为&str,Windows路径前缀属于合法UTF-8字符串,此处转换安全可靠。

运行输出

提取到的raw前缀: D:

内容的提问来源于stack exchange,提问作者Monty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:10:34