Compare commits

...

4 Commits

Author SHA1 Message Date
90f6fdad97
RBE custom types structs activity 2 2021-09-11 20:00:34 -04:00
c57baae2cc
RBE custom types structs activity 1 2021-09-11 13:52:45 -04:00
013a8faa2f
RBE custom types structs 2021-09-11 13:42:09 -04:00
798575d9ef
RBE primitives array 2021-09-11 13:35:25 -04:00
3 changed files with 108 additions and 0 deletions

View File

@ -1,4 +1,7 @@
/custom_types/*
/hello/*
/primitives/*
!/custom_types/*.rs
!/hello/*.rs
!/primitives/*.rs

View File

@ -0,0 +1,79 @@
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
struct Unit;
struct Pair(i32, f32);
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
#[derive(Debug)]
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn rect_area(r: Rectangle) -> f32 {
(r.top_left.x - r.bottom_right.x) * (r.top_left.y - r.bottom_right.y)
}
fn square(p: &Point, d: f32) -> Rectangle {
Rectangle {
top_left: Point { x: p.x + d, y: p.y },
bottom_right: Point { x: p.x, y: p.y + d },
}
}
fn main() {
let name = String::from("Peter");
let age = 27;
let peter = Person { name, age };
println!("{:?}", peter);
let point: Point = Point { x: 10.3, y: 0.4 };
println!("point coordinates: ({}, {})", point.x, point.y);
let bottom_right = Point { x: 5.2, y: 0.2 };
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
let Point {
x: left_edge,
y: top_edge,
} = point;
let rect = Rectangle {
top_left: Point {
x: left_edge,
y: top_edge,
},
bottom_right: bottom_right,
};
let _unit = Unit;
let pair = Pair(1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
println!("rect in {:?}", rect);
println!("area of rect is {}", rect_area(rect));
let lower_left = Point { x: 4.1, y: 11.3 };
let d = 7.7f32;
let sq = square(&lower_left, d);
println!("sq from point={:?} of d={} is {:?}", lower_left, d, sq);
}

View File

@ -0,0 +1,26 @@
use std::mem;
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
fn main() {
let xs: [i32; 5] = [1, 2, 3, 4, 5];
let ys: [i32; 500] = [0; 500];
println!("first element of the array: {}", xs[0]);
println!("second element of the array: {}", xs[1]);
println!("number of elements in the array: {}", xs.len());
println!("array occupies {} bytes", mem::size_of_val(&xs));
println!("borrow the whole array as a slice");
analyze_slice(&xs);
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1..4]);
// println!("{}", xs[5]);
}