如何编写一个返回 Vec<Path> 的函数? [英] How to write a function that returns Vec<Path>?
问题描述
我正在阅读文档并尝试编写一些基本的文件 I/O 代码作为帮助我学习 Rust 的工具.
I'm reading the documentation and trying to write some basic file I/O code as a vehicle to help me learn 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
中的Path
的集合?
How should I write this function to return the collection of Path
s inside the Path
that's passed in?
推荐答案
你没有.Path
是一种没有大小的类型,只能通过间接方式使用(例如 &Path
或 Box
).从这个意义上说,它就像 str
或 [u8]
类型——两者都不能直接使用,只能间接使用.
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.
您可能想要的是 PathBuf
,表示拥有的路径.它相当于 &str
的 String
和 &[u8]
的 Vec
.
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"));
}
另见:
这篇关于如何编写一个返回 Vec<Path> 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!