【发布时间】:2016-04-11 15:33:47
【问题描述】:
我在 Rust 中有一个使用 try! 的函数,它尝试递归地收集目录中的所有文件并将它们插入到向量中。因为函数使用try! 来检查错误,编译器似乎期望函数返回io::Result,并且不允许我包含向量,因为try! 宏只返回结果。我需要返回向量。
代码如下:
mod os{
use std::io;
use std::fs::{self, DirEntry};
//use std::fs;
use std::path::Path;
// one possible implementation of walking a directory only visiting files
pub fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> (io::Result<()>,Vec<String>) {
let mut filevec: Vec<String> = Vec::new();
if try!(fs::metadata(dir)).is_dir() {
for entry in try!(fs::read_dir(dir)) {
let entry = try!(entry);
if try!(fs::metadata(entry.path())).is_dir() {
try!(visit_dirs(&entry.path(), cb));
} else {
cb(&entry);
}
}
}
(Ok(()),filevec)
}
fn push_path_to_vec(p:&DirEntry,v:Vec<String>){
v.push(p.path().to_str().unwrap().to_string());
}}
这是错误:
<std macros>:5:8: 6:42 error: mismatched types:
expected `(core::result::Result<(), std::io::error::Error>, collections::vec::Vec<collections::string::String>)`
found `core::result::Result<_, _>`
(expected tuple,
found enum `core::result::Result`) [E0308]
我想知道是否有任何我错过的惯用方法。
【问题讨论】:
-
您可能需要以下功能:
pub fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<Vec<String>>。注意Vec<String>现在是如何包含在结果中的。 -
顺便说一句,我认为你的问题的标题并不完全准确,因为它不是关于在函数中返回多个值,对吧?
-
可能不会。我会改的。
标签: vector error-handling rust