-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_Method_Syntax.rs
More file actions
39 lines (33 loc) · 835 Bytes
/
12_Method_Syntax.rs
File metadata and controls
39 lines (33 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Step 1: Define a struct
struct Student {
name: String,
age: u8,
}
// Step 2: Implement methods using 'impl' block
impl Student {
// Method to display details
fn show(&self) {
println!("Name: {}, Age: {}", self.name, self.age);
}
// Method to check if student is adult
fn is_adult(&self) -> bool {
self.age >= 18
}
// Method that takes mutable self
fn birthday(&mut self) {
self.age += 1;
}
}
fn main() {
// Create an instance
let mut s1 = Student {
name: String::from("Raushan"),
age: 19,
};
// Call methods
s1.show(); // Name: Raushan, Age: 17
println!("Adult? {}", s1.is_adult()); // false
s1.birthday(); // age +1
s1.show(); // Name: Raushan, Age: 18
println!("Adult? {}", s1.is_adult()); // true
}