Posts

Showing posts with the label Structs

Struct Methods

Introduction: In Rust, structs not only store data but also offer the flexibility of defining methods, akin to functions, that can manipulate and utilize the data within a struct. Methods, like functions, can accept parameters and return values. However, they are distinguished by being defined within the context of a struct, with the first parameter always being a reference to the struct itself. This allows methods to directly access and manipulate the data stored within a specific struct instance. Defining Methods: To define methods within a struct, Rust utilizes the impl keyword followed by the struct type's name. Within this implementation block, methods can be declared to perform various operations on the struct's data. For instance, consider a method get_name defined within a Shuttle struct, which retrieves and returns the shuttle's name as a string slice. struct Shuttle { name: String, propellant: f64, } impl Shuttle { fn get_name(&self) -> ...

Defining Structs

Structs in Rust provide a powerful way to organize and manage data in your programs. Unlike tuples, structs allow you to name each field, making it easier to work with complex data structures. In this post, we'll explore how to define structs, create instances, access fields, and manage memory allocation. Defining Structs To define a struct in Rust, you use the struct keyword followed by the name of the struct. Inside the curly braces, you define the fields of the struct, each with a name and its associated data type. struct Shuttle { name: String, crew_size: u8, propellant: f64, } In this example, we've defined a Shuttle struct with fields for the shuttle's name (a String ), crew size (a u8 ), and propellant (a f64 ). Creating Instances Once you've defined a struct, you can create instances of it by providing concrete values for each field. let mut vehicle = Shuttle { name: String::from("Endeavor"), crew_size: 7, propellant: 835958....