Structs Flashcards
What is a struct?
A custom data type that lets you name and package together multiple related values that make up a meaningful group.
What are the names and types of the pieces of data inside a struct?
fields
How do you create an instance of a struct?
by specifying concrete values for each of the fields.
How do you get a specific value from a struct?
Using dot notation
Can certain fields in a struct be marked mutable?
No, the entire instance must be mutable.
What type of syntax is used to specify a property and its value that have the same name, as in: struct { name, email }
field init shorthand syntax
How do you create a new instance of a struct that uses most of the values of a previous instance?
Using struct update syntax: let user2 = User { email: "someone@someplace.com", username: "johnsonw", ...user1, }
What are tuple structs?
They have the added meaning the struct name provides but don’t have names associated with their fields. These are useful when you want to give the tuple a name such that it is different from other tuples.
struct Color(i32, i32, i32); struct Point(i32, i32, i32);
How do you access an element on a tuple or tuple struct?
By using a “.” followed by an index to access an individual value.
What is a unit struct?
A struct that doesn’t have any fields
When is a unit struct useful?
when you need to implement a trait on some type but don’t have any data that you want to store in the type itself
Should structs own most of their data?
Generally, we want instances of a struct to own all of its data and for that data to be valid for as long as the entire struct is valid.
Can data in a struct store a reference to data owned by something else?
Yes, but to do so requires the use of lifetimes.
What does a lifetime guarantee for a struct?
Lifetimes ensure that the data referenced by a struct is valid for as long as the struct is.
Should you prefer taking ownership of a struct or borrowing it?
You should prefer borrowing a struct.