debugrustCritical
What is unwrap in Rust, and what is it used for?
Viewed 0 times
unwrapandusedforrustwhat
Problem
I have this code that uses
After looking at the definition of
And the signature of
Am I correct in understanding that
.unwrap():fn main() {
let paths = std::fs::read_dir("/home/user").unwrap();
for path in paths {
println!("Name: {}", path.unwrap().path().display());
}
}After looking at the definition of
unwrap,pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
}
}And the signature of
read_dirpub fn read_dir>(path: P) -> io::ResultAm I correct in understanding that
unwrap returns the T type that is passed in Result?Solution
In Rust, when you have an operation that may either return a
The function
It is best used when you are positively sure that you don't have an error. If that is not the case usually it is better either pattern-match the error or use the
In your example, the call to
With
Look how every error case is checked.
(Updated to use
T or fail, you will have a value of type Result or Option (E will be the error condition in case of an interesting error).The function
unwrap(self) -> T will give you the embedded T if there is one. If instead there is not a T but an E or None then it will panic.It is best used when you are positively sure that you don't have an error. If that is not the case usually it is better either pattern-match the error or use the
try! macro ? operator to forward the error.In your example, the call to
read_dir() returns a io::Result because opening the directory might fail. And iterating the opened directory returns multiple values of type io::Result because reading the directory might also fail.With
try! ? it would be something like this:fn try_main() -> std::io::Result {
let entries = std::fs::read_dir("/home/user")?;
for entry in entries {
println!("Name: {}", entry?.path().display());
}
Ok(())
}
fn main() {
let res = try_main();
if let Err(e) = res {
println!("Error: {}", e);
}
}Look how every error case is checked.
(Updated to use
? instead of try!(). The macro still works, but the ? is preferred for new code).Code Snippets
fn try_main() -> std::io::Result<()> {
let entries = std::fs::read_dir("/home/user")?;
for entry in entries {
println!("Name: {}", entry?.path().display());
}
Ok(())
}
fn main() {
let res = try_main();
if let Err(e) = res {
println!("Error: {}", e);
}
}Context
Stack Overflow Q#36362020, score: 240
Revisions (0)
No revisions yet.