LukeMathWalker / zero-to-production

Code for "Zero To Production In Rust", a book on API development using Rust.
https://www.zero2prod.com
Apache License 2.0
5.73k stars 491 forks source link

Test code in 7.7.2.1 doesn't compile #80

Closed emiddleton closed 3 years ago

emiddleton commented 3 years ago

In 7.7.2.1 Red Test the test code won't compile because body is a &str and so can't be indexed by a &str.

#[actix_rt::test]
async fn subscribe_sends_a_confirmation_email_with_a_link() {
    // [...] 
    let body = std::str::from_utf8(&email_request.body).unwrap();
    // Extract the link from one of the request fields.
    let get_link = |s: &str| {
        let links: Vec<_> = linkify::LinkFinder::new()
            .links(s)
            .filter(|l| *l.kind() == linkify::LinkKind::Url)
            .collect();
            assert_eq!(links.len(), 1);
        links[0].as_str().to_owned()
    };

    let html_link = get_link(&body["HtmlBody"].as_str().unwrap());
    let text_link = get_link(&body["TextBody"].as_str().unwrap());
    // The two links should be identical
    assert_eq!(html_link, text_link);
}

The compile error I got was

error[E0277]: the type `str` cannot be indexed by `&str`
   --> tests/api/subscriptions.rs:125:31
    |
125 |     let html_link = get_link(&body["HtmlBody"].as_str().unwrap());
    |                               ^^^^^^^^^^^^^^^^ string indices are ranges of `usize`
    |
    = help: the trait `SliceIndex<str>` is not implemented for `&str`
    = note: required because of the requirements on the impl of `Index<&str>` for `str`

error[E0277]: the type `str` cannot be indexed by `&str`
   --> tests/api/subscriptions.rs:126:31
    |
126 |     let text_link = get_link(&body["TextBody"].as_str().unwrap());
    |                               ^^^^^^^^^^^^^^^^ string indices are ranges of `usize`
    |
    = help: the trait `SliceIndex<str>` is not implemented for `&str`
    = note: required because of the requirements on the impl of `Index<&str>` for `str`
emiddleton commented 3 years ago

Sorry just noticed this is the same issue as #77