blob: 3b0ab98966a107e2b51832531ab11e43d2b65b25 (
plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// First parameter for methods must be named 'self', but the
// implementation provides some aliases like:
//
// self == self: Self
// &self == self: &Self
//
// Note though that 'Self' is just an alias for the type referenced
// by the impl{} block. So, here:
//
// impl Rectangle {}
// ^ Self is an alias to Rectangle
fn can_hold(&self, r: &Rectangle) -> bool {
self.width > r.width && self.height > r.height
}
// Here we can pass just a reference to a struct
// Rectangle, no need to transfer ownership
fn area(self: &Rectangle) -> u32 {
self.width * self.height
}
// Associated functions can be defined without a self parameter
// so they function can be namespaced with ::
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}
fn main() {
let rect = Rectangle {
width: dbg!(5 * 10),
height: 3,
};
let sqrt = Rectangle::square(90);
println!("{rect:#?} Area: {}", rect.area());
dbg!(&rect);
dbg!(&sqrt);
println!("{}", sqrt.can_hold(&rect));
}
|