Use ? instead of unwrap in examples (#458)

This is recommended by the Rust API Guidelines:

https://rust-lang.github.io/api-guidelines/documentation.html#examples-use--not-try-not-unwrap-c-question-mark

One exception: When we need to unwrap an Option, the examples still use
.unwrap(). The alternative would be something like
`.ok_or(SomeErrorHere)?`, which feels like an awkward way to deal with
an Option. This might get better with NoneError:

https://docs.rs/rustc-std-workspace-std/1.0.1/std/option/struct.NoneError.html

I also rearranged some examples that used turbofish to use type
annotations. I think type annotations are more familiar to early Rust
users (and they use fewer characters and less punctuation, which is
always nice).
This commit is contained in:
Jacob Hoffman-Andrews
2021-12-19 20:04:30 -08:00
committed by GitHub
parent 2563df4f62
commit 2df70168c4
5 changed files with 21 additions and 14 deletions

View File

@@ -242,14 +242,15 @@ impl Response {
///
/// ```
/// use std::io::Read;
/// # fn main() -> Result<(), ureq::Error> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # ureq::is_test(true);
/// let resp = ureq::get("http://httpbin.org/bytes/100")
/// .call()?;
///
/// assert!(resp.has("Content-Length"));
/// let len = resp.header("Content-Length")
/// .and_then(|s| s.parse::<usize>().ok()).unwrap();
/// let len: usize = resp.header("Content-Length")
/// .unwrap()
/// .parse()?;
///
/// let mut bytes: Vec<u8> = Vec::with_capacity(len);
/// resp.into_reader()
@@ -632,15 +633,18 @@ impl FromStr for Response {
///
/// Example:
/// ```
/// # fn main() -> Result<(), ureq::Error> {
/// let s = "HTTP/1.1 200 OK\r\n\
/// X-Forwarded-For: 1.2.3.4\r\n\
/// Content-Type: text/plain\r\n\
/// \r\n\
/// Hello World!!!";
/// let resp = s.parse::<ureq::Response>().unwrap();
/// let resp: ureq::Response = s.parse()?;
/// assert!(resp.has("X-Forwarded-For"));
/// let body = resp.into_string().unwrap();
/// let body = resp.into_string()?;
/// assert_eq!(body, "Hello World!!!");
/// # Ok(())
/// # }
/// ```
fn from_str(s: &str) -> Result<Self, Self::Err> {
let stream = Stream::from_vec(s.as_bytes().to_owned());