Structs
Defining a struct
Structs hold named fields; there is no βclassβ with inheritance. Similar to C# structs or classes used as data containers.
struct User {
name: String,
age: u32,
active: bool,
}In C#: Like a class or struct with properties: class User { public string Name; public int Age; public bool Active; }.
Creating instances
let user = User {
name: String::from("Alice"),
age: 30,
active: true,
};In C#: Like object initializer: new User { Name = "Alice", Age = 30, Active = true }.
Accessing fields
println!("{}", user.name);
user.age; // immutable by defaultIn C#: Same idea as user.Name. In Rust, mutability is per binding: let mut user = ... if you want to change fields.
impl blocks: methods
Methods are defined in impl blocks. &self = immutable receiver, &mut self = mutable, self = ownership.
impl User {
fn greet(&self) -> String {
format!("Hi, I'm {}", self.name)
}
fn have_birthday(&mut self) {
self.age += 1;
}
}
user.greet();In C#: Like instance methods; &self is like this, &mut self like this when the object is mutable. Rust has no this keyword; use self.
Associated functions (no self)
Functions in impl that take no self are like static methods:
impl User {
fn new(name: String, age: u32) -> Self {
User { name, age, active: true }
}
}
let u = User::new(String::from("Bob"), 25);In C#: Like a static factory method or constructor.
Common pitfalls
- Printing a struct needs a derive.
println!("{:?}", user)only compiles if the struct derivesDebug: add#[derive(Debug)].{}(Display) is not derivable β implement it by hand, or stick to{:?}/{:#?}(pretty-printed) while debugging. - Fields are private outside their module by default. A field needs
pubto be read or set from another module (see module 37) β there are no auto-generated getters/setters.
In C#: most objects have a usable ToString() and show up in the debugger out of the
box; in Rust you opt into formatting with #[derive(Debug)].
Key takeaway
Structs are data + impl for methods. Use &self / &mut self / self for methods; use Self and no self for constructors/factories. No inheritance; use traits for abstraction.