https://www.snoyman.com/blog/2018/10/rust-crash-course-01-kick-the-tires-solutions

I also blog frequently on the Yesod Web Framework blog, as well as the FP Complete blog.

See a typo? Have a suggestion? Edit this page on Github

Below are the solutions to the exercises from the last Rust Crash Course lesson, “Kick the Tires.”

This post is part of a series based on teaching Rust at FP Complete. If you’re reading this post outside of the blog, you can find links to all posts in the series at the top of the introduction post. You can also subscribe to the RSS feed.

Exercise 1

The following code is broken:

fn main() {
    let val: String = String::from("Hello, World!");
    printer(val);
    printer(val);
}

fn printer(val: String) {
    println!("The value is: {}", val);
}

We got an error message about a move. We’ll learn more about moves in the next lesson, when we discuss ownership. There are two basic solutions. First, the less-than-ideal one:

Clone

We’ve moved the original val into the first call to printer, and can’t use it again. One workaround is to instead move a clone of val into that call, leaving the original unaffected:

fn main() {
    let val: String = String::from("Hello, World!");
    printer(val.clone());
    printer(val);
}

fn printer(val: String) {
    println!("The value is: {}", val);
}

Notice that I only cloned val the first time, not the second time. We don’t need val again after the second call, so it’s safe to move it. Using an extra clone is expensive, since it requires allocating memory and performing a buffer copy.

Speaking of it being expensive…

Pass by reference

Instead of moving the value, we can instead pass it into the printer function by reference. Let’s first try to achieve that by just modifying printer:

fn main() {
    let val: String = String::from("Hello, World!");
    printer(val);
    printer(val);
}

fn printer(val: String) {
    println!("The value is: {}", val);
}

This doesn’t work, because when we call printer, we’re still giving it a String and not a reference to a String. Fixing that is pretty easy:

fn main() {
    let val: String = String::from("Hello, World!");
    printer(&val);
    printer(&val);
}