Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasbs17 committed Jun 20, 2024
1 parent caf6e94 commit df6d632
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ edition = "2021"

[[bin]]
name = "hello_world"
path = "src/hello_world.rs"
path = "src/hello_world.rs"

[[bin]]
name = "structures"
path = "src/structures.rs"
76 changes: 76 additions & 0 deletions src/structures.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// An attribute to hide warnings for unused code.
#![allow(dead_code)]

#[derive(Debug)]
struct Person {
name: String,
age: u8,
}

// A unit struct
struct Unit;

// A tuple struct
struct Pair(i32, f32);

// A struct with two fields
struct Point {
x: f32,
y: f32,
}

// Structs can be reused as fields of another struct
struct Rectangle {
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
top_left: Point,
bottom_right: Point,
}

fn main() {
// Create struct with field init shorthand
let name = String::from("Peter");
let age = 27;
let peter = Person { name, age };

// Print debug struct
println!("{:?}", peter);

// Instantiate a `Point`
let point: Point = Point { x: 10.3, y: 0.4 };
let another_point: Point = Point { x: 5.2, y: 0.2 };

// Access the fields of the point
println!("point coordinates: ({}, {})", point.x, point.y);

// Make a new point by using struct update syntax to use the fields of our
// other one
let bottom_right = Point { x: 5.2, ..another_point };

// `bottom_right.y` will be the same as `point.y` because we used that field
// from `point`
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);

// Destructure the point using a `let` binding
let Point { x: left_edge, y: top_edge } = point;

let _rectangle = Rectangle {
// struct instantiation is an expression too
top_left: Point { x: left_edge, y: top_edge },
bottom_right: bottom_right,
};

// Instantiate a unit struct
let _unit = Unit;

// Instantiate a tuple struct
let pair = Pair(1, 0.1);

// Access the fields of a tuple struct
println!("pair contains {:?} and {:?}", pair.0, pair.1);

// Destructure a tuple struct
let Pair(integer, decimal) = pair;

println!("pair contains {:?} and {:?}", integer, decimal);
}
Binary file added structures.exe
Binary file not shown.

0 comments on commit df6d632

Please sign in to comment.