How to write a function that returns Vec?

后端 未结 1 580
刺人心
刺人心 2021-01-06 02:46

I\'m reading the documentation and trying to write some basic file I/O code as a vehicle to help me learn Rust.

The following doesn\'t compile:

use s         


        
相关标签:
1条回答
  • 2021-01-06 03:26

    You don't. Path is a type that has no size, and is only usable through indirection (such as &Path or Box<Path>). In this sense, it is like the type str or [u8] — neither can be directly used, only indirectly.

    What you probably want is a PathBuf, which represents an owned path. It is the equivalent of String for &str and Vec<u8> for &[u8].

    After changing the return type, you have to properly map the results of the iterator to create your desired type:

    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"));
    }
    
    0 讨论(0)
提交回复
热议问题