1. 21
    Rustlings structs2: Filling in the unspecified fields in structs with update syntax
    1m 47s

Rustlings structs2: Filling in the unspecified fields in structs with update syntax

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise.

Chris Biscardi: [0:00] Structs2 is a similar setup in that it asks us to address all the TODOs, to make the test pass. Let's take a look at the code that we have. We have an Order struct that has a number of fields of different values -- Booleans, u32 bit integers, Strings. We derive(Debug). We have a create_order_template() function. That looks like it's called on line 36 as well.

[0:19] It returns one of these orders with a set of default values. In our tests, we can see that we have an order_template that's created with these default values, a number of assertions, and a TODO statement that tells us to create our own order using the update syntax and template above.

[0:34] We have order_template already. We're going to take order. All we're going to do is use this object Rust spread-type syntax that uses two dots with the name of the template. What this does is what's called update syntax.

[0:48] Order is a struct. Any of the fields that we haven't specified values for are filled in by order_template which is these default values. Now that we have our fill-in, we can take a look at the tests that are passing, and say panicked at 'assertion failed: (left = right)', left: "Bob", right: "Hacker in Rust."

[1:04] We're asserting that your_order.name is equal to "Hacker in Rust," whereas the order_template gives us "Bob." Let's specify our name to be "Hacker in Rust." We've passed that test. See what's happening here is that we're instantiating a new order. We're specifying the name of this new order is "Hacker in Rust" and any of the fields that we haven't specified are these default values.

[1:29] Let's finish up. Note that all of the rest of the assertions except for the count are the same as the default value. Also note that if you're used to object Rust spread syntax from other languages, that's not the way this works. We cannot put this order_template update syntax at the beginning of our record. It has to be at the end.