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.

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, and blue so 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

structs3.rs

  • In this exercise we need to fix two method.

  • First is is_international, based on the test if sender_country and recipient_country is different the it considered as international, and expected return type is bool.

  • Second is get_fees, based on the test the formula of fees is weight_in_grams * cents_per_gram and expected return type is u32.

Last updated