-
Notifications
You must be signed in to change notification settings - Fork 58
/
main.rs
56 lines (50 loc) · 1.6 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
{
let rect = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of a {}x{} rectangle is {} pixels.",
rect.width,
rect.height,
// area(rect), // this code is moving rect to area
area(&rect), // but with this one, area is borrowing the rect
);
// if the area didn't borrow the rect,
// the main would never use it again.
// println!("{}", rect.width);
}
println!();
// ----------------------------------------------------------------------
{
// Rust provides a number of traits for us to use with the derive
// annotation that can add useful behavior to our custom types.
// DEBUGGING STRUCTS
#[derive(Debug)] // With this Debug trait, println can print
// an instance of the Rectangle struct.
struct Rectangle {
width: u32,
height: u32,
}
let rect = Rectangle {
width: 25,
height: 15,
};
println!("{:?}", rect); // You just need to use {:?} instead of {}.
println!("{:#?}", rect); // Prettier output.
}
}
// this function just immutably borrows a rectangle instance.
// it doesn't own the instance.
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
// this function signature is taking the ownership of a rectangle instance.
// fn area(rectangle: Rectangle) -> u32 {
// rectangle.width * rectangle.height
// }