Rust Cheat Sheet

Home

Struct

Summary

Definition


Access to the field of a Struct instance

dot notation


There are 3 types of Structs


Using the "Field Init Shorthand"

Classic C Struct

Create a Classic C Struct

          struct <name of Struct> {
              name1: type,
              name2: type,
              name3: type,
          }
        

Create an instance of a Classic C Struct

          let <name of instance> = <name of Struct> {
              name1: value,
              name2: value,
              name3: value,
          };
        

Note:

  • note the semicolon at the end.
  • The syntax <name of ...> refers to the name given to the element,
    which is written without angles.
  • By convention, a struct name always begins with a capital letter.

Tuple Struct

Create a Tuple Struct

          struct <name of Struct>(type, type, type, ...);
        

Create an instance of a Tuple Struct

          let <name of instance> = <name of Struct>(value, value, value, ...);
        

Note:

  • note the semicolon at the end (create and instance).
  • The syntax <name of ...> refers to the name given to the element,
    which is written without angles.

Unit Struct

Create a Unit Struct

          struct <name of Struct>;
        

Create an instance of a Unit Struct

          let <name of instance> = <name of Struct>;
        

Note:

  • note the semicolon at the end (create and instance).
  • The syntax <name of ...> refers to the name given to the element,
    which is written without angles.
  • By convention, a struct name always begins with a capital letter.

Field Init Shorthand

Example with a function that returns a "User" instance of a "User Struct"

            fn build_user(email: String, username: String) -> User {
                User {
                    active: true,
                    username, // because the parameter name in the function's signature and the Struct field name are exactly the same, we can use the "field init shorthand".
                    email, // "field init shorthand" can also applied here.
                    sign_in_count: 1,
                }
            }
          

Struct Update Syntax

"When a new instance is created that includes most of its values from another instance"

            let user2 = User {
                email: String::from("another@example.com"),
                ..user1 // all values except the email value are the same as user1.
            };