From 60689fd10385a31909fdef5f7d77afda3699a3cd Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Mon, 5 Sep 2016 22:33:22 -0400 Subject: [PATCH] 2.2 with activity --- rustbyexample/022/Cargo.lock | 4 +++ rustbyexample/022/Cargo.toml | 6 ++++ rustbyexample/022/src/main.rs | 54 +++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 rustbyexample/022/Cargo.lock create mode 100644 rustbyexample/022/Cargo.toml create mode 100644 rustbyexample/022/src/main.rs diff --git a/rustbyexample/022/Cargo.lock b/rustbyexample/022/Cargo.lock new file mode 100644 index 0000000..3808199 --- /dev/null +++ b/rustbyexample/022/Cargo.lock @@ -0,0 +1,4 @@ +[root] +name = "022" +version = "0.1.0" + diff --git a/rustbyexample/022/Cargo.toml b/rustbyexample/022/Cargo.toml new file mode 100644 index 0000000..f900ba9 --- /dev/null +++ b/rustbyexample/022/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "022" +version = "0.1.0" +authors = ["Dan Buch "] + +[dependencies] diff --git a/rustbyexample/022/src/main.rs b/rustbyexample/022/src/main.rs new file mode 100644 index 0000000..62e381e --- /dev/null +++ b/rustbyexample/022/src/main.rs @@ -0,0 +1,54 @@ +use std::fmt; + +fn reverse(pair: (i32, bool)) -> (bool, i32) { + let (integer, boolean) = pair; + (boolean, integer) +} + +fn transpose(matrix: Matrix) -> Matrix { + Matrix(matrix.0, matrix.2, matrix.1, matrix.3) +} + +#[derive(Debug)] +struct Matrix(f32, f32, f32, f32); + +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "( {} {} )\n( {} {} )", self.0, self.1, self.2, self.3) + } +} + +fn main() { + let long_tuple = (1u8, 2u16, 3u32, 4u64, + -1i8, -2i16, -3i32, -4i64, + 0.1f32, 0.2f64, + 'a', true); + + println!("long tuple first value: {}", long_tuple.0); + println!("long tuple second value: {}", long_tuple.1); + + let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); + + println!("tuple of tuples: {:?}", tuple_of_tuples); + + let pair = (1, true); + println!("pair is {:?}", pair); + + println!("the reversed pair is {:?}", reverse(pair)); + + println!("one element tuple: {:?}", (5u32,)); + println!("just an integer: {:?}", (5u32)); + + 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); + + println!("Matrix:\n{}", matrix); + println!("Transpose:\n{}", transpose(matrix)); +}