How to write a function that returns a Vec <Path>?

I am reading the documentation and trying to write some basic file I / O code as a tool to help me learn Rust.

The following does not compile:

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())
}

With compilation error:

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`

How do I write this function to return the collection Pathinside Paththat passed in?

+4
source share
1 answer

No. Pathis a type that has no size and can only be used by means of indirection (for example, &Pathor Box<Path>). In this sense, it looks like a type stror [u8]- none of them can be used directly, only indirectly.

, , , PathBuf, . String &str Vec<u8> &[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"));
}
+6

All Articles