【问题标题】:How to write a function that returns Vec<Path>?如何编写返回 Vec<Path> 的函数?
【发布时间】:2016-05-25 13:54:23
【问题描述】:

我正在阅读文档并尝试编写一些基本的文件 I/O 代码作为帮助我学习 Rust 的工具。

以下内容无法编译:

use std::fs;
use std::io;
use std::path::Path;

pub fn read_filenames_from_dir<P>(path: P) -> Result<Vec<Path>, io::Error>
where
    P: AsRef<Path>,
{
    let paths = try!(fs::read_dir(path));
    Ok(paths.unwrap())
}

出现编译错误:

error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path`
  --> src/main.rs:5:1
   |
5  | / pub fn read_filenames_from_dir<P>(path: P) -> Result<Vec<Path>, io::Error>
6  | | where
7  | |     P: AsRef<Path>,
8  | | {
9  | |     let paths = try!(fs::read_dir(path));
10 | |     Ok(paths.unwrap())
11 | | }
   | |_^ `[u8]` does not have a constant size known at compile-time
   |
   = help: within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`
   = note: required because it appears within the type `std::path::Path`
   = note: required by `std::vec::Vec`

我应该如何编写这个函数来返回传入的Path 中的Paths 集合?

【问题讨论】:

    标签: rust


    【解决方案1】:

    你没有。 Path 是一种没有大小的类型,只能通过间接方式使用(例如&amp;PathBox&lt;Path&gt;)。从这个意义上说,它就像str[u8] 类型——两者都不能直接使用,只能间接使用。

    您可能想要的是一个PathBuf,它代表一个拥有 路径。它相当于String&amp;strVec&lt;u8&gt;&amp;[u8]

    更改返回类型后,您必须正确映射迭代器的结果以创建所需的类型:

    use std::{
        fs, io,
        path::{Path, PathBuf},
    };
    
    pub fn read_filenames_from_dir<P>(path: P) -> Result<Vec<PathBuf>, io::Error>
    where
        P: AsRef<Path>,
    {
        fs::read_dir(path)?
            .into_iter()
            .map(|x| x.map(|entry| entry.path()))
            .collect()
    }
    
    fn main() {
        println!("{:?}", read_filenames_from_dir("/etc"));
    }
    

    另见:

    【讨论】:

    • 什么路径?进行源代码潜水,我知道Path 包含OsStr,其中包含一个名为sys::os_str::Slice 的东西,我找不到它的实际定义。我认为它基本上是在 [u8]? 之上的几层抽象?
    • @Jsor 基本上是 [u8] 上的几层抽象 — 是的,on Unix-like platforms。视窗is different。这一点抽象在 OPs 错误消息中泄漏:“core::marker::Sized 没有为[u8] 类型实现”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2021-12-28
    相关资源
    最近更新 更多