1. 20
    Rustlings structs1: Instantiating Classic, Tuple, and Unit structs
    2m 9s

Rustlings structs1: Instantiating Classic, Tuple, and Unit structs

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise.

Chris Biscardi: [0:00] We have quite a bit of code in structs1, including an empty struct here that we need to put something into, a TupleStruct here that we also need to put something into, and a UnitStruct that derives(Debug).

[0:10] On line 15, our tests start. Each of these tests, we're going to instantiate one of our structs, whether it's a classic struct, a tuple struct, or the unit struct that derives(Debug) above. The errors that Rust gives us don't really help us here because we already have these TODOs comments to tell us what to do.

[0:26] In this case, we've got green.name and green.hex. For our first struct in our first test, this struct refers to our ColorClassicStruct. We'll take a first string into this by naming them Strings. Note that we also need to instantiate a new struct.

[0:39] Note that the errors that the Rust compiler is looking at have moved down to line 37, which indicates that our test was passing, that there weren't any problems with it.

[0:47] What we've done here is created a struct with two fields on it that are name and hex. These values are strings, which means that the struct is going to own these.

[0:54] To create a string, we use String: :from and pass in a string literal. Note that if we don't use String: :from, Rust will tell us we're using mismatched types on lines 24 and 25. We could also use a type &str here, but we're going to stick with Strings and use String: :from.

[1:09] Next, we have to do our TupleStruct. Our TupleStruct is currently empty, but it uses the same values. You can see that we access the tuple via tuple indexes, like we did in some of the primitive exercises.

[1:19] We're going to end up using the same types that we did in our ClassicStruct, but note that they aren't named where we have name and hex in our ClassicStruct. Our TupleStruct is dependent on the position. If we go back down to our test, we can instantiate our struct.

[1:33] Now, that we've instantiated our ClassicStruct, our TupleStruct, and our tests are passing, we can move on to the UnitStruct. The UnitStruct was created for us, and there's nothing else we needed to do.

[1:43] Note that this is called a UnitStruct because it doesn't have any fields like the TupleStruct has some, and the Classic one also has some. Since our UnitStruct doesn't have any fields, we can set unit_struct = UnitStruct, and it works.

[1:56] If we try to take the same approach that we did with the UnitStruct with our ClassicStruct which does have fields, you'll note that Rust gives us an error. You'll note the Rust compiler informs us that ColorClassicStruct does in fact have fields and that we need to include them here.