Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Rust by Example
- https://doc.rust-lang.org/stable/rust-by-example/
- Collection of solved activities from the Rust by Example book
- */
- /*
- Questions
- 9.2.1. Capturing
- https://doc.rust-lang.org/stable/rust-by-example/fn/closures/capture.html
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2bae19b86f57bd5a08f04645e48d6069
- */
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 1.2. Formatted print
- https://doc.rust-lang.org/stable/rust-by-example/hello/print.html
- Print a float with a given precision println!("{pi:.N}")
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=98026c4b84e9a36bc8de3f3ff2ec6238
- */
- fn main() {
- let pi = 3.141592; // round to third
- println!("Pi is roughly {pi:.3}");
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 1.2.2. Display
- https://doc.rust-lang.org/stable/rust-by-example/hello/print/print_display.html
- Implement fmt::Display for custom struct
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4535be35f1f50120faa302f7c9ec1b01
- */
- use std::fmt; // Import `fmt`
- #[derive(Debug)]
- struct Complex {
- real: f64,
- imag: f64,
- }
- // Implement `Display` for `Complex`
- impl fmt::Display for Complex {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{0} + {1}i", self.real, self.imag)
- }
- }
- fn main() {
- let complex_num = Complex { real: 3.3, imag: 7.2};
- println!("Display: {}", complex_num);
- println!("Debug: {:?}", complex_num);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 1.2.2.1. Testcase: List
- https://doc.rust-lang.org/stable/rust-by-example/hello/print/print_display/testcase_list.html
- Modify the implementation of fmt::Display for a list-like struct to display indexes next to values
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b3ee1e88f382f65f45f4ff74f6dda5b1
- */
- use std::fmt; // Import the `fmt` module.
- // Define a structure named `List` containing a `Vec`.
- struct List(Vec<i32>);
- impl fmt::Display for List {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- // Extract the value using tuple indexing,
- // and create a reference to `vec`.
- let vec = &self.0;
- write!(f, "[")?;
- // Iterate over `v` in `vec` while enumerating the iteration
- // count in `count`.
- for (count, v) in vec.iter().enumerate() {
- // For every element except the first, add a comma.
- // Use the ? operator to return on errors.
- if count != 0 { write!(f, ", ")?; }
- write!(f, "{0}: {1}", count, v)?;
- }
- // Close the opened bracket and return a fmt::Result value.
- write!(f, "]")
- }
- }
- fn main() {
- let v = List(vec![1, 2, 3]);
- println!("{}", v);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 1.2.3. Formatting
- https://doc.rust-lang.org/stable/rust-by-example/hello/print/fmt.html
- Implement fmt::Display for the Color struct so that both the RGB tuple and hex representation are shown
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0b5857134428e2d4824c1807a496ab71
- */
- use std::fmt::{self, Formatter, Display};
- struct Color {
- red: u8,
- green: u8,
- blue: u8,
- }
- impl Display for Color {
- // `f` is a buffer, and this method must write the formatted string into it
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- // `write!` is like `format!`, but it will write the formatted string
- // into a buffer (the first argument)
- write!(f, "RGB ({0}, {1}, {2}) 0x{0:0>2X}{1:0>2X}{2:0>2X}", self.red, self.green, self.blue)
- }
- }
- fn main() {
- for color in [
- Color { red: 128, green: 255, blue: 90 },
- Color { red: 0, green: 3, blue: 254 },
- Color { red: 0, green: 0, blue: 0 },
- ].iter() {
- println!("{}", *color);
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 2.2. Tuples
- https://doc.rust-lang.org/stable/rust-by-example/primitives/tuples.html
- 1. Implement fmt::Display trait for the Matrix struct
- 2. Implement transpose() for the 2x2 matrices of the Matrix struct
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=72949ad5fd23f92da73f8a1e8f980ad3
- */
- use std::fmt;
- // Tuples can be used as function arguments and as return values
- fn reverse(pair: (i32, bool)) -> (bool, i32) {
- // `let` can be used to bind the members of a tuple to variables
- let (integer, boolean) = pair;
- (boolean, integer)
- }
- fn transpose(matrix: Matrix) -> Matrix {
- Matrix(matrix.0, matrix.2, matrix.1, matrix.3) // 2
- }
- // The following struct is for the activity.
- #[derive(Debug)]
- struct Matrix(f32, f32, f32, f32);
- impl fmt::Display for Matrix {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "({0} {1})\n({2} {3})", self.0, self.1, self.2, self.3) // Backslash is AltGr+' // 1
- }
- }
- fn main() {
- // A tuple with a bunch of different types
- let long_tuple = (1u8, 2u16, 3u32, 4u64,
- -1i8, -2i16, -3i32, -4i64,
- 0.1f32, 0.2f64,
- 'a', true);
- // Values can be extracted from the tuple using tuple indexing
- println!("long tuple first value: {}", long_tuple.0);
- println!("long tuple second value: {}", long_tuple.1);
- // Tuples can be tuple members
- let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
- // Tuples are printable
- println!("tuple of tuples: {:?}", tuple_of_tuples);
- // But long Tuples (more than 12 elements) cannot be printed
- // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
- // println!("too long tuple: {:?}", too_long_tuple);
- // TODO ^ Uncomment the above 2 lines to see the compiler error
- let pair = (1, true);
- println!("pair is {:?}", pair);
- println!("the reversed pair is {:?}", reverse(pair));
- // To create one element tuples, the comma is required to tell them apart
- // from a literal surrounded by parentheses
- println!("one element tuple: {:?}", (5u32,));
- println!("just an integer: {:?}", (5u32));
- //tuples can be destructured to create bindings
- let tuple = (1, "hello", 4.5, true);
- let (a, b, c, d) = tuple;
- println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
- let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
- println!("{:?}", matrix);
- println!("Matrix:\n{}", matrix);
- println!("Transpose:\n{}", transpose(matrix));
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 3.1. Structs
- https://doc.rust-lang.org/stable/rust-by-example/custom_types/structs.html
- 1. Implement rect_area() for Rectangle structs
- 2. Implement square() that from a Point and a float returns a Rectangle... that is a square
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=424032cd98d5f107d83aae52b6254be4
- */
- // Attributes to hide warnings for unused code and unused variables.
- #![allow(dead_code)]
- #![allow(unused_variables)]
- #[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(rect: &Rectangle) -> f32 {
- let Rectangle {
- top_left: Point { x: x1, y: y1 },
- bottom_right: Point { x: x2, y: y2 } } = rect;
- ((x2-x1)*(y2-y1)).abs() // 1
- }
- fn square(top_left_corner: Point, side_length: f32) -> Rectangle {
- let Point { x: x1, y: y1 } = top_left_corner;
- Rectangle {
- top_left: Point { x: x1, y: y1 },
- bottom_right: Point {
- x: x1 + side_length,
- y: y1 + side_length
- }
- } // 2
- }
- 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 rect1 = Rectangle {
- top_left: Point { x: 0.0, y: 0.0 },
- bottom_right: Point { x: 10.0, y: 15.0 },
- };
- let area = rect_area(&rect1);
- println!("{:?} has area {}", rect1, area);
- let square1 = square(point, 10.0);
- let area = rect_area(&square1);
- println!("{:?} has area {}", square1, area);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- 8.6. if let
- https://doc.rust-lang.org/stable/rust-by-example/flow_control/if_let.html
- Replace if .. == .. by if let .. = .. so that a conditional can be used on the non-parametrized enum var
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6d19880b6cb267d64ce9c638e4b65f3f
- */
- // This enum purposely neither implements nor derives PartialEq.
- // That is why comparing Goo::Bar == a fails below.
- enum Goo {Bar}
- fn main() {
- let a = Goo::Bar;
- // Variable a matches Goo::Bar
- if let Goo::Bar = a {
- println!("a is goobar");
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
- /*
- */
- ////////////////////////////////////////////////////////////////////////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement