CH 5. Using Structs to Structure Related Data Flashcards
What is a struct in Rust?
A struct is a custom data type that allows you to group related data together.
How do you define a struct in Rust?
By using the struct keyword followed by the name of the struct and a list of its fields.
What is the purpose of the impl block in Rust?
The impl block is used to define methods on a struct, allowing you to specify behavior associated with the struct.
What is the difference between associated functions and methods in Rust?
Associated functions are defined within the impl block but don’t have a self parameter. They are often used as constructors. Methods, on the other hand, have a self parameter and can access and modify the instance of the struct.
What is the self keyword in Rust?
The self keyword represents an instance of a struct within its methods.
What is the purpose of the & symbol in method parameters?
The & symbol denotes a reference to the struct instead of taking ownership of it. This allows borrowing the data without moving or copying it.
How can you define a tuple struct in Rust?
A tuple struct is defined by using the struct keyword followed by the name and specifying the types of the fields without naming them.
struct Triangle(u32, u32, u32)
What is the #[derive] attribute used for?
The #[derive] attribute allows you to automatically implement common traits, such as Debug or Clone, for a struct.