rust


How do I access files in a directory in Rust?


I've written a pretty straight-forward script based on the Rust docs:
use std::fs::{self, DirEntry};
use std::path::Path;
fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
println!("directory found!");
}
}
}
but I get the following compile errors about ?:
error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
--> test.rs:6:18
|
6 | for entry in fs::read_dir(path)? {
| -------------------
| |
| the trait `std::ops::Carrier` is not implemented for `()`
| in this macro invocation
|
= note: required by `std::ops::Carrier::from_error`
error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
--> test.rs:7:21
|
7 | let entry = entry?;
| ------
| |
| the trait `std::ops::Carrier` is not implemented for `()`
| in this macro invocation
|
= note: required by `std::ops::Carrier::from_error`
I only partially understand ? but I know the gist is that it allows you to act on a Result only if it's an Ok. The error here is that it's being used on a () rather than a Result, which is weird. I tried implementing the loop without ?:
use std::fs::{self, DirEntry};
use std::path::Path;
fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path) {
println!("{}", entry.path());
}
}
But I get the error:
error: no method named `path` found for type `std::fs::ReadDir` in the current scope
--> test.rs:7:30
|
7 | println!("{}", entry.path());
| ^^^^
Which implies that instead of fs::read_dir returning ReadDir which is an iterator over DirEntry items, fs::read_dir is returning () which is somehow an iterator over ReadDir items?
I'm so confused.
It's probably worth mentioning that i'm running: rustc 1.16.0 (30cf806ef 2017-03-10)
The first error is because you cannot use try! or ? in a function returning ().
The second error is because read_dir returns a Result:
pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir>
Result implements IntoIterator, so path is actually the iterator you think you had.
Handling the errors and calling Path::display gets you what you want:
use std::fs;
use std::path::Path;
fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path).expect("Unable to list") {
let entry = entry.expect("unable to get entry");
println!("{}", entry.path().display());
}
}
The ? operator and the try! macro will only work when your function returns a Result (in which the raised errors can be properly converted, of course). The main function does not return a result.
You may wish to send all of your code to a separate function and handle the error in main(), with something like this:
use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;
fn main() {
run().unwrap_or_else(|e| {
println!("Something went wrong: {}", e.to_string());
});
}
fn run() -> io::Result<()> {
let path = Path::new(".");
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
println!("directory found!");
}
}
Ok(())
}

Related Links

How to slice a large Vec<i32> as &[u8]?
How to parse i64 from a string? [duplicate]
Why is variable scope dependent on the definition order?
Warning on “unstable” directive
How can I pass a socket as an argument to a function being called within a thread?
error: cannot move out of borrowed content on &mut self
Why does a reference not live long enough in case of “as_slice”?
Getting the error “error: the trait `core::marker::Sized` is not implemented” when trying to return the value from a vector
Traits with associated type in templates
Error handling best-practices
How to call count on an iterator and still use the iterator's items?
Caught between a lifetime and an FFI place
How to swap elements of array?
error: cannot assign to immutable indexed content `i[..]`
How to make a vector of received size?
Make an argument of type BTreeMap optional [closed]

Categories

HOME
opengl
oracle
android-espresso
apache-nifi
verification
ontouchlistener
facebook-messenger
long-integer
hid
theano
biztalk
odata
android-emulator
autocomplete
yql
header
swift2
mosquitto
mithril.js
responsive-design
elastic-load-balancer
lda
heuristics
alljoyn
graphdb
angular4
freertos
spring-jpa
jodatime
sonata
varnish-vcl
multiple-tables
cmake-gui
tableview
backtracking
liferay-6.2
software-packaging
web-push
fusetools
network-analysis
marquee
oracleforms
python-imageio
macromedia
bonita
sparkle
microprocessors
intune
d3.js-v4
quickcheck
cloudera-manager
wdk
stackpanel
nsuserdefaults
code-rally
variable-variables
tidal-scheduler
iscroll
newtons-method
yoast
contactless-smartcard
git-tfs
react-intl
bit-shift
comm
gestures
ptvs
polymaps
front-camera
wildfly-9
haraka
seccomp
msbuild-4.0
nsdata
piping
perforce-integrate
adp
codecharge
android-async-http
preferenceactivity
vim-plugin
flask-security
openshift-cartridge
gluon-desktop
vdm-sl
compositetype
dynamics-ax-2012-r2
componentart
findersync
datagridcomboboxcolumn
producer
ecos
nidaqmx
osascript
webmethod
xcode6.3.1
webaii
radius-protocol
mod-perl
jmenubar
mousemotionlistener
insertion
dibs
cmath
session-0-isolation
system-requirements
uitextfielddelegate
image-scanner
navigationcontroller
groovy-console
space-partitioning
mongrel2
aggregator
tabbarcontroller
raw-data
yahoo-maps
regioninfo

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App