Posts

Showing posts with the label Encapsulation

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) -> ...