Browse Source

Add rectangles example

master
Georg Hopp 6 years ago
parent
commit
fe29428f65
Signed by: ghopp GPG Key ID: 4C5D226768784538
  1. 9
      rectangles/Cargo.toml
  2. 90
      rectangles/src/main.rs

9
rectangles/Cargo.toml

@ -0,0 +1,9 @@
[package]
name = "rectangles"
version = "0.1.0"
authors = ["Georg Hopp <georg@steffers.org>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

90
rectangles/src/main.rs

@ -0,0 +1,90 @@
//
// Examples related to structs…
//
// Georg Hopp <georg@steffers.org>
//
// Copyright © 2019 Georg Hopp
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, inner: &Rectangle) -> bool {
self.width >= inner.width && self.height >= inner.height
}
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let width1 = 30;
let height1 = 50;
println!(
"The area of the rectangle ist {} square pixels.",
area(width1, height1));
let rect1 = (30, 50);
println!(
"The area of the rectangle ist {} square pixels.",
_area(rect1));
let rect1 = Rectangle { width: 30, height: 50 };
println!(
"The area of the rectangle ist {} square pixels.",
__area(&rect1));
println!("_rect1 is {:?}", rect1);
println!(
"The area of the rectangle ist {} square pixels.",
rect1.area());
let rect2 = Rectangle { width: 10, height: 40};
let rect3 = Rectangle { width: 60, height: 45};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
let square1 = Rectangle::square(32);
println!("Got the square rectange: {:?}", square1);
}
fn area(width: u32, height: u32) -> u32 {
width * height
}
fn _area(dimensions: (u32, u32)) -> u32 {
let (width, height) = dimensions;
width * height
}
fn __area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
Loading…
Cancel
Save