Hands-on Rust: confused about loop / vector section (p36)

Hello,

As a Rust beginner I felt confused about Looping Until You Call Break / Adding New Vector Entries page 36. The body of the main() function isn’t completely shown there and I’m unable to wrap my head around the problem. Clippy is also complaining about what I wrote. Can someone provide the explicit code of the main() function please?

Thank you.

Arthur

1 Like

Hi! Thanks for buying the book.

You can find all the source code in a zip file on the book’s PragProg page: Hands-on Rust: Effective Learning through 2D Game Development and Play by Herbert Wolverson

I’ve also packaged it up for easy browsing on Github: GitHub - thebracket/HandsOnRust: The source code that accompanies Hands-on Rust: Effective Learning throug

The filenames in the blue/green bar at the top of code snippets point to the filename referred to by the code in that snippet. The one you’re looking for is this file.

The main function looks like this:

fn main() {
    let mut visitor_list = vec![
        Visitor::new("Bert", "Hello Bert, enjoy your treehouse."),
        Visitor::new("Steve", "Hi Steve. Your milk is in the fridge."),
        Visitor::new("Fred", "Wow, who invited Fred?"),
    ];

    loop {
        println!("Hello, what's your name? (Leave empty and press ENTER to quit)");
        let name = what_is_your_name();

        let known_visitor = visitor_list.iter().find(|visitor| visitor.name == name);
        match known_visitor {
            Some(visitor) => visitor.greet_visitor(),
            None => {
                if name.is_empty() {    // (1)
                    break;  // (2)
                } else {
                    println!("{} is not on the visitor list.", name);
                    visitor_list.push(Visitor::new(&name, "New friend"));
                }
            }
        }
    }

    println!("The final list of visitors:");
    println!("{:#?}", visitor_list);
}

Hope that helps!
Herbert

1 Like

Hello Herbert,

Thank you for the fast reply and the link to the Github repo. It’s now working.

Greetings,

Arthur

1 Like