Structs Flashcards
What is a struct?
A type this is composed of other types.
How are structs different then tuples?
Each value in a struct is named.
What keyword is used to create a struct?
struct.
What is the syntax for creating a struct?
struct struct_name {
field_name: type,
}
How do we create an instance of a struct?
State the name of the struct and then add curly brackets containing key: value pairs, where the keys are the names of the fields and the values are the data we want to store in those fields.
How do we access a specific value from a struct?
dot notation. e.g. user.email
What is the field init short hand
Pattern that allows for only writing the variable name when assigning it to a struct field if they share the same name. email: email can be written as just email.
What is the struct update syntax?
Any fields not explicitly set can be set from another struct instance with .. e.g. let user2 = User { email foo: String::from("bar"), ..user1 };
What is a tuple struct
A tuple that is named. Individual fields are not named.
When are tuple structs useful?
When you want to give the whole tuple a name and make the tuple be a different type from other tuples, and naming each field as in a regular struct would be verbose or redundant.
What are unit-like structs
structs without any fields.
When are unit-like structs useful?
Situations in which you need to implement a trait on some type but don’t have any data that you want to store in the type itself.
How are methods different than functions?
They are declared within the context of a struct, enum, or trait object and their first parameter is always self.
How do we define a function within the context of a struct?
We start an impl (implementation) block. e.g. impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
What is the first parameter to a method?
self.