Structs
Struct:
Structs are user-defined types that allow you to group related data together similar to tuples.
Unlike with tuples, in a struct you’ll name each piece of data so it’s clear what the values mean.
Adding these names means that structs are more flexible than tuples so you don’t have to rely on the order of the data to specify or access the values of an instance.
Structs can have associated methods, which are functions tied to the struct.
Have struct update syntax capabilities using
...Types of struct in Rust are:
Regular Struct: Fields are explicitly named.
Tuple Struct: Fields are identified by their position (like a tuple).
Unit-Like Struct: A struct with no field.
Method:
Methods are similar to functions: we declare them with the fn keyword and a name.
Unlike functions, methods are defined within the context of a struct (or an enum or a trait object)
Their first parameter is always self, which represents the instance of the struct the method is being called on.
References:
structs1.rs
In this exercise we will define 3 types of struct.
First is regular struct.
Based on the test, it expect 3 fields
red,green, andblueso we can define it like this:
Second is tuple struct.
Based on the test, it also expect 3 fields, so we define it like this:
And last is unit-like struct.
It's already defined and we just need to instantiate it like this:
structs2.rs
In this exercise we need to create an
Orderfromorder_templateby using struct update syntax.So based on test we only need change
nameandcountso we do it like this:You can read more about it here: Creating Instances from Other Instances with Struct Update Syntax.
structs3.rs
In this exercise we need to fix two method.
First is
is_international, based on the test ifsender_countryandrecipient_countryis different the it considered as international, and expected return type isbool.Second is
get_fees, based on the test the formula of fees isweight_in_grams * cents_per_gramand expected return type isu32.
Last updated