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?