-
Notifications
You must be signed in to change notification settings - Fork 70
/
main.rs
39 lines (33 loc) · 877 Bytes
/
main.rs
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
struct User {
name: String,
surname: String,
}
impl User {
// "Static creation method" is actually a Rust's idiomatic way to define a "constructor".
pub fn new(name: String, surname: String) -> Self {
Self { name, surname }
}
// Constructs an object by reading from database.
pub fn load(id: u32) -> Self {
if id == 42 {
Self {
name: "John".into(),
surname: "Smith".into(),
}
} else {
panic!()
}
}
pub fn name(&self) -> &String {
&self.name
}
pub fn surname(&self) -> &String {
&self.surname
}
}
fn main() {
let alice = User::new("Alice".into(), "Fisher".into());
let john = User::load(42);
println!("{} {}", alice.name(), alice.surname());
println!("{} {}", john.name(), john.surname());
}