Skip to content

Instantly share code, notes, and snippets.

@giacomorebecchi
Created August 5, 2023 19:09
Show Gist options
  • Save giacomorebecchi/a744807c45316c37001b056f9ea39af1 to your computer and use it in GitHub Desktop.
Save giacomorebecchi/a744807c45316c37001b056f9ea39af1 to your computer and use it in GitHub Desktop.
My solution to Rust By Example (RBE) 3.1. Custom Types - Structures https://doc.rust-lang.org/rust-by-example/custom_types/structs.html
// 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
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[derive(Debug)]
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 rect_area(rectangle: &Rectangle) -> f32 {
let Rectangle {
top_left: Point {
x: top_left_x,
y: top_left_y,
},
bottom_right:
Point {
x: bottom_right_x,
y: bottom_right_y,
},
} = rectangle;
let area: f32 = (bottom_right_x - top_left_x) * (top_left_y - bottom_right_y);
return area;
}
fn square(point: Point, size: f32) -> Rectangle {
Rectangle {
top_left: Point {
y: point.y + size,
..point
},
bottom_right: Point {
x: point.x + size,
..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 };
// 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, ..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);
let area = rect_area(&_rectangle);
println!("Area of the rectangle {:?} is: {}", _rectangle, area);
let square_ret = square(point, 2.0);
println!("Squared {:?}", square_ret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment