Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not using unwrap() result in an error? [duplicate]

Tags:

types

rust

Using Rust 1.11.0, I get the error:

error: no method named read_to_string found for type std::result::Result<std::fs::File, std::io::Error> in the current scope

when I'm not using unwrap():

use std::io::prelude::*;
use std::fs::File;

fn main() {
    let mut f = File::open("D:/test/rust/io.txt"); // Error thrown here
    let mut s = String::new();
    f.read_to_string(&mut s);
    println!("{}", s);
}

This works fine:

use std::io::prelude::*;
use std::fs::File;

fn main() {
    let mut f = File::open("D:/test/rust/io.txt").unwrap();
    let mut s = String::new();
    f.read_to_string(&mut s); // Warning thrown here
    println!("{}", s);
}

But it also gives a warning so I have to add another unwrap() after read_to_string():

use std::io::prelude::*;
use std::fs::File;

fn main() {
    let mut f = File::open("D:/test/rust/io.txt").unwrap();
    let mut s = String::new();
    f.read_to_string(&mut s).unwrap(); // Notice the 2nd unwrap here
    println!("{}", s);
}

What's happening here?

like image 481
kosinix Avatar asked Sep 08 '16 07:09

kosinix


1 Answers

It's because read_to_string() is a method available for types implementing the io::Read trait. What you are attempting to use it on is a Result<fs::File, io::Error> which does not implement it.

When you call unwrap() on a Result<T, E>, it yields T - in this case fs::File that does implement io::Read.

The warning you are getting when you don't call unwrap() on f.read_to_string(&mut s) is because the type Result<T, E> it returns has an attribute #[must_use] which means that it can not just be discarded; you can perform the following "ignoring" assignment to not get the warning:

let _ = f.read_to_string(&mut s);

like image 71
ljedrz Avatar answered Nov 15 '22 07:11

ljedrz