more struct methods, receiving another struct

This commit is contained in:
Tyrel Souza 2023-02-27 00:13:07 -05:00
parent 92b1c38688
commit b5dec65244
No known key found for this signature in database
GPG Key ID: F3614B02ACBE438E
2 changed files with 71 additions and 10 deletions

45
rectangles/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,45 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'rectangles'",
"cargo": {
"args": [
"build",
"--bin=rectangles",
"--package=rectangles"
],
"filter": {
"name": "rectangles",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'rectangles'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=rectangles",
"--package=rectangles"
],
"filter": {
"name": "rectangles",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}

View File

@ -1,17 +1,33 @@
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect = Rectangle { width: 30, height:50};
println!(
"The area of a rectangle is {} square pixels",
area(&rect)
);
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, r2: &Rectangle) -> bool {
self.width > r2.width && self.height > r2.height
}
}
// MAIN
fn main() {
let rect1 = Rectangle { width:30, height:50};
let rect2 = Rectangle { width:10, height:40};
let rect3 = Rectangle { width:60, height:45};
println!("r: {}", rect1.area());
println!("r: {}", rect2.area());
println!("r: {}", rect3.area());
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}