如何编写一个返回Vec <Path>的函数?

Gav*_*ope 5 rust

我正在阅读文档并尝试编写一些基本文件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())
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

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`
Run Code Online (Sandbox Code Playgroud)

我该怎么写这个函数来返回传入的Paths里面的集合Path

She*_*ter 8

你没有.Path是一种没有大小的类型,只能通过间接(例如&PathBox<Path>)使用.从这个意义上说,它就像是类型str[u8]- 既不能直接使用,也不能间接使用.

您可能想要的是a PathBuf,它代表一个拥有的路径.它相当于Stringfor &strVec<u8>for &[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"));
}
Run Code Online (Sandbox Code Playgroud)

  • @Jsor *基本上是 [u8]* 上的几个抽象层 - 是的,[在类 Unix 平台上](https://github.com/rust-lang/rust/blob/1.8.0/src/libstd/ sys/unix/os_str.rs#L27-L29)。Windows [不同](https://github.com/rust-lang/rust/blob/1.8.0/src/libstd/sys/windows/os_str.rs#L46-L48)。这一点抽象在 OP 错误消息中泄漏了:“`core::marker::Sized` 没有为类型 `[u8]` 实现”。 (2认同)