1

I am learning Rust with little previous coding experience. I am stuck on a simple recipe from the Rust cookbook: making a HTTP GET request.

I am trying to use the Result type to catch errors instead of using .unwrap, which is far from ideal from what I have read.

The code kind of works, but I want to learn how to implement the Result type on the line let mut res = reqwest::get(uri):

extern crate reqwest;
use std::error::Error;
use std::io::Read;

fn main() {
    let url = "http://www.somedomain.com";
    println!("Getting source for: {} ", url);
    get(url);
}

fn get(uri: &str) -> Result<(), Box<dyn Error>> {
    let mut res = reqwest::get(uri).unwrap();
    let mut body = String::new();
    res.read_to_string(&mut body);

    println!("Status: {}\n", res.status());
    println!("Headers : \n {:#?}", res.headers());
    println!("Body : \n\n {:#?}", body);

    Ok(())
}

The only examples I have found seem to use the match keyword which I don't think is right in this case.

let x = match somecondition {
    Ok() => { /* ....... */ }
    Err() => { /* ....... */ }
};

How can I achieve what I am trying?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
NickDa
  • 57
  • 5
  • 3
    Maybe this helps: https://stackoverflow.com/questions/42917566/what-is-this-question-mark-operator-about – hellow Aug 08 '19 at 14:36
  • I think it makes more sense now , so if i was to add the ? to these two lines : 1) let mut res = reqwest::get(uri).unwrap(); ( remove unwrap and add ? ) 2) res.read_to_string(&mut body); And then modified where i call the function to look something like let f = get(url); let f = match f { Ok(file) => file, Err(error) => error , }; Would this be more along the correct lines ? – NickDa Aug 08 '19 at 14:51
  • 2
    sounds okay-ish. You can diretly write `match get(url) { ... }` but yes, that's what you basically do. – hellow Aug 08 '19 at 14:58
  • The code that you *already have* works fine if you [replace `unwrap` with `?`](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d19035e601b704009c6ce51023b37f17). You can even [return it all the way up and out of main](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9dbac48ae8fd6e511e7312b5d05192d3). – Shepmaster Aug 08 '19 at 16:58

0 Answers0