我想将目录名称列表传递给函数,如下所示:
use std::path::Path;
fn test(dirs: &Vec<Path>) {}
fn main() {
let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")];
test(dirs);
}
Run Code Online (Sandbox Code Playgroud)
但是它不能编译:
<anon>:3:5: 4:6 error: the trait bound `[u8]: std::marker::Sized` is not satisfied [E0277]
<anon>:3 fn test(dirs: &Vec<Path>) {
<anon>:4 }
<anon>:3:5: 4:6 help: see the detailed explanation for E0277
<anon>:3:5: 4:6 note: `[u8]` does not have a constant size known at compile-time
<anon>:3:5: 4:6 note: required because it appears within the type `std::sys::os_str::Slice`
<anon>:3:5: 4:6 note: required because it appears within the type `std::ffi::OsStr`
<anon>:3:5: 4:6 note: required because it appears within the type `std::path::Path`
<anon>:3:5: 4:6 note: required by `std::vec::Vec`
Run Code Online (Sandbox Code Playgroud)
看起来像路径Sized吗?
如果我不想传递Vec<String>给函数,该如何解决?也许PathBuf吧?如何以生锈的方式实现这一目标?
事实上,Path是一个无大小的类型,就像str. 几乎使用 a 的唯一明智的方法Path是引用它:(&Path就像&str)。所以你的例子看起来像这样:
use std::path::Path;
fn test(dirs: &[&Path]) {}
fn main() {
let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")];
test(&dirs);
}
Run Code Online (Sandbox Code Playgroud)
并不是说我也将其更改&Vec<_>为&[_]. 对 a 的引用Vec并不比切片 ( &[_]) 更强大,因此惯用的方法是传递切片而不是对向量的引用。
如果您不想将所有权转移给该test函数,则上述解决方案是正确的方法。如果你想转移所有权(包括实际保存路径数据的字符串缓冲区),你应该使用PathBuf.
| 归档时间: |
|
| 查看次数: |
732 次 |
| 最近记录: |