├── Chapter01 ├── code │ ├── welcome.rs │ └── welcomec │ │ ├── .gitignore │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ └── main.rs └── exercises │ ├── name.rs │ ├── name │ ├── .gitignore │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs │ └── smallest_program.rs ├── Chapter02 ├── code │ ├── alias.rs │ ├── bindings.rs │ ├── comments.rs │ ├── constants1.rs │ ├── constants2.rs │ ├── expressions.rs │ ├── mutable_constant.rs │ ├── references.rs │ ├── scope.rs │ ├── test.rs │ ├── type_conversions.rs │ ├── type_errors.rs │ └── types2.rs └── exercises │ ├── change_constant.rs │ ├── compound_let.rs │ └── formatting.rs ├── Chapter03 ├── code │ ├── attributes_cfg.rs │ ├── attributes_testing.rs │ ├── cube │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── src │ │ │ ├── lib.rs │ │ │ └── tests.rs │ │ └── tests │ │ │ └── lib.rs │ ├── doc │ │ ├── .lock │ │ ├── COPYRIGHT.txt │ │ ├── FiraSans-LICENSE.txt │ │ ├── FiraSans-Medium.woff │ │ ├── FiraSans-Regular.woff │ │ ├── Heuristica-Italic.woff │ │ ├── Heuristica-LICENSE.txt │ │ ├── LICENSE-APACHE.txt │ │ ├── LICENSE-MIT.txt │ │ ├── SourceCodePro-LICENSE.txt │ │ ├── SourceCodePro-Regular.woff │ │ ├── SourceCodePro-Semibold.woff │ │ ├── SourceSerifPro-Bold.woff │ │ ├── SourceSerifPro-LICENSE.txt │ │ ├── SourceSerifPro-Regular.woff │ │ ├── exdoc │ │ │ ├── cube.v.html │ │ │ ├── fn.cube.html │ │ │ ├── index.html │ │ │ └── sidebar-items.js │ │ ├── jquery.js │ │ ├── main.css │ │ ├── main.js │ │ ├── normalize.css │ │ ├── rustdoc.css │ │ ├── search-index.js │ │ └── src │ │ │ └── exdoc │ │ │ └── exdoc.rs.html │ ├── exdoc.rs │ ├── fib_procedural.rs │ ├── functions.rs │ ├── ifelse.rs │ ├── loops.rs │ ├── mylib │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ └── nested_function.rs └── exercises │ ├── absolute.rs │ ├── ifreturn.rs │ └── iftest.rs ├── Chapter04 ├── code │ ├── arguments.rs │ ├── arrays.rs │ ├── destructure_enum.rs │ ├── destructuring_structs.rs │ ├── enums.rs │ ├── enums2.rs │ ├── input.rs │ ├── match_tuple.rs │ ├── pattern_match.rs │ ├── pattern_match2.rs │ ├── remove_elem_vector.rs │ ├── strings.rs │ ├── structs.rs │ └── tuples.rs └── exercises │ ├── chars_string.rs │ ├── match_type.rs │ ├── matching.rs │ ├── monster.rs │ ├── pattern_match.rs │ └── tuples_ex.rs ├── Chapter05 ├── code │ ├── adapters_consumers.rs │ ├── dispatch.rs │ ├── error_div.rs │ ├── errors.rs │ ├── generics.rs │ ├── higher_functions.rs │ ├── input_number.rs │ ├── input_number2.rs │ ├── iterators.rs │ ├── sqrt_match.rs │ └── try_input_number.rs └── exercises │ ├── complex.rs │ ├── draw_trait.rs │ ├── fold.rs │ └── range_next.rs ├── Chapter06 ├── code │ ├── builder_pattern.rs │ ├── constructor_pattern.rs │ ├── dispatch.rs │ ├── impl_add.rs │ ├── method_enum.rs │ ├── methods.rs │ ├── paradigm.rs │ ├── super_traits.rs │ ├── trait_constraints │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ ├── src │ │ │ └── trait_constraints.rs │ │ └── target │ │ │ └── debug │ │ │ ├── .cargo-lock │ │ │ ├── .fingerprint │ │ │ ├── libc-2903dbbf6aef2ddf │ │ │ │ ├── dep-lib-libc-2903dbbf6aef2ddf │ │ │ │ ├── lib-libc-2903dbbf6aef2ddf │ │ │ │ └── lib-libc-2903dbbf6aef2ddf.json │ │ │ ├── libc-51e019ba1c48043b │ │ │ │ ├── dep-lib-libc-51e019ba1c48043b │ │ │ │ ├── lib-libc-51e019ba1c48043b │ │ │ │ └── lib-libc-51e019ba1c48043b.json │ │ │ ├── num-5589f3536e774f5d │ │ │ │ ├── dep-lib-num-5589f3536e774f5d │ │ │ │ ├── lib-num-5589f3536e774f5d │ │ │ │ └── lib-num-5589f3536e774f5d.json │ │ │ ├── num-bigint-0600fe7406f6efc3 │ │ │ │ ├── dep-lib-num_bigint-0600fe7406f6efc3 │ │ │ │ ├── lib-num_bigint-0600fe7406f6efc3 │ │ │ │ └── lib-num_bigint-0600fe7406f6efc3.json │ │ │ ├── num-bigint-549b3dc61a1ab09c │ │ │ │ ├── dep-lib-num_bigint-549b3dc61a1ab09c │ │ │ │ ├── lib-num_bigint-549b3dc61a1ab09c │ │ │ │ └── lib-num_bigint-549b3dc61a1ab09c.json │ │ │ ├── num-complex-c6ee85dc30c1af34 │ │ │ │ ├── dep-lib-num_complex-c6ee85dc30c1af34 │ │ │ │ ├── lib-num_complex-c6ee85dc30c1af34 │ │ │ │ └── lib-num_complex-c6ee85dc30c1af34.json │ │ │ ├── num-complex-edf2967894911149 │ │ │ │ ├── dep-lib-num_complex-edf2967894911149 │ │ │ │ ├── lib-num_complex-edf2967894911149 │ │ │ │ └── lib-num_complex-edf2967894911149.json │ │ │ ├── num-ded7f16ba22e8735 │ │ │ │ ├── dep-lib-num-ded7f16ba22e8735 │ │ │ │ ├── lib-num-ded7f16ba22e8735 │ │ │ │ └── lib-num-ded7f16ba22e8735.json │ │ │ ├── num-integer-133aa4776c28e844 │ │ │ │ ├── dep-lib-num_integer-133aa4776c28e844 │ │ │ │ ├── lib-num_integer-133aa4776c28e844 │ │ │ │ └── lib-num_integer-133aa4776c28e844.json │ │ │ ├── num-integer-27c2de924efa446c │ │ │ │ ├── dep-lib-num_integer-27c2de924efa446c │ │ │ │ ├── lib-num_integer-27c2de924efa446c │ │ │ │ └── lib-num_integer-27c2de924efa446c.json │ │ │ ├── num-iter-89e152564970c817 │ │ │ │ ├── dep-lib-num_iter-89e152564970c817 │ │ │ │ ├── lib-num_iter-89e152564970c817 │ │ │ │ └── lib-num_iter-89e152564970c817.json │ │ │ ├── num-iter-ecbfdf4df71f0e1c │ │ │ │ ├── dep-lib-num_iter-ecbfdf4df71f0e1c │ │ │ │ ├── lib-num_iter-ecbfdf4df71f0e1c │ │ │ │ └── lib-num_iter-ecbfdf4df71f0e1c.json │ │ │ ├── num-rational-01cc31e8816a22bc │ │ │ │ ├── dep-lib-num_rational-01cc31e8816a22bc │ │ │ │ ├── lib-num_rational-01cc31e8816a22bc │ │ │ │ └── lib-num_rational-01cc31e8816a22bc.json │ │ │ ├── num-rational-3cf12afed100f639 │ │ │ │ ├── dep-lib-num_rational-3cf12afed100f639 │ │ │ │ ├── lib-num_rational-3cf12afed100f639 │ │ │ │ └── lib-num_rational-3cf12afed100f639.json │ │ │ ├── num-traits-1297a437aebb5e06 │ │ │ │ ├── dep-lib-num_traits-1297a437aebb5e06 │ │ │ │ ├── lib-num_traits-1297a437aebb5e06 │ │ │ │ └── lib-num_traits-1297a437aebb5e06.json │ │ │ ├── num-traits-2ab8385458bc0c23 │ │ │ │ ├── dep-lib-num_traits-2ab8385458bc0c23 │ │ │ │ ├── lib-num_traits-2ab8385458bc0c23 │ │ │ │ └── lib-num_traits-2ab8385458bc0c23.json │ │ │ ├── rand-92319875a3b5e926 │ │ │ │ ├── dep-lib-rand-92319875a3b5e926 │ │ │ │ ├── lib-rand-92319875a3b5e926 │ │ │ │ └── lib-rand-92319875a3b5e926.json │ │ │ ├── rand-ef4d4ec4f3682cc9 │ │ │ │ ├── dep-lib-rand-ef4d4ec4f3682cc9 │ │ │ │ ├── lib-rand-ef4d4ec4f3682cc9 │ │ │ │ └── lib-rand-ef4d4ec4f3682cc9.json │ │ │ ├── rustc-serialize-07daa0fc98cd1a5d │ │ │ │ ├── dep-lib-rustc_serialize-07daa0fc98cd1a5d │ │ │ │ ├── lib-rustc_serialize-07daa0fc98cd1a5d │ │ │ │ └── lib-rustc_serialize-07daa0fc98cd1a5d.json │ │ │ ├── rustc-serialize-6e8c8043064c4717 │ │ │ │ ├── dep-lib-rustc_serialize-6e8c8043064c4717 │ │ │ │ ├── lib-rustc_serialize-6e8c8043064c4717 │ │ │ │ └── lib-rustc_serialize-6e8c8043064c4717.json │ │ │ ├── trait_constraints-639f937b259be757 │ │ │ │ ├── bin-trait_constraints-639f937b259be757 │ │ │ │ ├── bin-trait_constraints-639f937b259be757.json │ │ │ │ └── dep-bin-trait_constraints-639f937b259be757 │ │ │ └── trait_constraints-82799a0b74ff0411 │ │ │ │ ├── bin-trait_constraints-82799a0b74ff0411 │ │ │ │ ├── bin-trait_constraints-82799a0b74ff0411.json │ │ │ │ └── dep-bin-trait_constraints-82799a0b74ff0411 │ │ │ ├── deps │ │ │ ├── liblibc-2903dbbf6aef2ddf.rmeta │ │ │ ├── liblibc-51e019ba1c48043b.rlib │ │ │ ├── libnum-5589f3536e774f5d.rlib │ │ │ ├── libnum-ded7f16ba22e8735.rmeta │ │ │ ├── libnum_bigint-0600fe7406f6efc3.rlib │ │ │ ├── libnum_bigint-549b3dc61a1ab09c.rmeta │ │ │ ├── libnum_complex-c6ee85dc30c1af34.rlib │ │ │ ├── libnum_complex-edf2967894911149.rmeta │ │ │ ├── libnum_integer-133aa4776c28e844.rlib │ │ │ ├── libnum_integer-27c2de924efa446c.rmeta │ │ │ ├── libnum_iter-89e152564970c817.rlib │ │ │ ├── libnum_iter-ecbfdf4df71f0e1c.rmeta │ │ │ ├── libnum_rational-01cc31e8816a22bc.rmeta │ │ │ ├── libnum_rational-3cf12afed100f639.rlib │ │ │ ├── libnum_traits-1297a437aebb5e06.rmeta │ │ │ ├── libnum_traits-2ab8385458bc0c23.rlib │ │ │ ├── librand-92319875a3b5e926.rlib │ │ │ ├── librand-ef4d4ec4f3682cc9.rmeta │ │ │ ├── librustc_serialize-07daa0fc98cd1a5d.rlib │ │ │ └── librustc_serialize-6e8c8043064c4717.rmeta │ │ │ ├── libtrait_constraints.d │ │ │ └── trait_constraints.d │ ├── traits.rs │ ├── visitor_pattern.rs │ └── write.rs └── exercises │ ├── complex.rs │ ├── draw_trait.rs │ └── visitor_pattern_dd.rs ├── Chapter07 ├── code │ ├── boxes1.rs │ ├── boxes2.rs │ ├── boxes_experimental.rs │ ├── clone.rs │ ├── drop.rs │ ├── lifetimes.rs │ ├── linked_list.rs │ ├── moving_closure.rs │ ├── ownership1.rs │ ├── ownership2.rs │ ├── ref.rs │ ├── ref_count_notgood.rs │ ├── refcount.rs │ └── references.rs └── exercises │ ├── dangling_pointer.rs │ ├── grow_a_tentacle.rs │ ├── increment_vector.rs │ ├── ownership3.rs │ └── pointer_mutability.rs ├── Chapter08 ├── code │ ├── builtin_macros.rs │ ├── import_modules.rs │ ├── libmycrate.rlib │ ├── libstructs.rlib │ ├── macro_debug.rs │ ├── macros.rs │ ├── mod_private.rs │ ├── modul1 │ │ └── mod.rs │ ├── modul2.rs │ ├── modules.rs │ ├── monsters │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── random │ │ ├── .gitignore │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── structs.rs │ ├── unimplemented.rs │ └── unreachable.rs └── exercises │ ├── macro_ex.rs │ └── priv_struct.rs ├── Chapter09 ├── code │ ├── change_vec.rs │ ├── channel_box.rs │ ├── channels.rs │ ├── channels2.rs │ ├── channels_struct.rs │ ├── make_channel.rs │ ├── many_threads.rs │ ├── many_threads │ │ ├── .gitignore │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── moving_closure.rs │ ├── not_shared.rs │ ├── panic_thread.rs │ ├── sync_channel.rs │ ├── thread_safe.rs │ └── thread_spawn.rs └── exercises │ ├── exc_thread_safe.rs │ └── shared_channel.rs ├── Chapter10 └── code │ ├── asm.rs │ ├── calling_clibrary.0.o │ ├── calling_clibrary.crate.allocator.o │ ├── calling_clibrary.crate.metadata.o │ ├── calling_clibrary.rs │ ├── calling_libc.rs │ ├── parsing_argument.rs │ ├── pointer_offset.rs │ ├── raw_pointers.rs │ ├── size_of_val.rs │ ├── swap.rs │ └── unsafe.rs ├── Chapter11 └── code │ ├── a │ └── b.txt │ ├── filesystem.rs │ ├── hashmaps.rs │ ├── hashsets.rs │ ├── hello.txt │ ├── info.txt │ ├── lorem_ipsum.txt │ ├── lorem_ipsum2.txt │ ├── numbers.txt │ ├── paths.rs │ ├── read_file.rs │ ├── read_file_try.rs │ ├── read_files_in_dir.rs │ ├── reading_text_file.rs │ ├── write_file.rs │ └── write_file_try.rs ├── Chapter12 └── code │ ├── file_time │ ├── .gitignore │ ├── Cargo.lock │ ├── Cargo.toml │ ├── log.txt │ └── src │ │ └── main.rs │ ├── mongodb.rs │ ├── mysql.rs │ ├── piston101 │ ├── .gitignore │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs │ └── web_dev.rs ├── LICENSE └── README.md /Chapter01/code/welcome.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Welcome to the Game!") 3 | } 4 | 5 | -------------------------------------------------------------------------------- /Chapter01/code/welcomec/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /Chapter01/code/welcomec/Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "welcomec" 3 | version = "0.1.0" 4 | 5 | -------------------------------------------------------------------------------- /Chapter01/code/welcomec/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "welcomec" 4 | version = "0.1.0" 5 | authors = ["Ivo Balbaert "] 6 | 7 | [[bin]] 8 | name = "welcome" 9 | 10 | [dependencies] -------------------------------------------------------------------------------- /Chapter01/code/welcomec/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /Chapter01/exercises/name.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("My name is John Smith"); 3 | } -------------------------------------------------------------------------------- /Chapter01/exercises/name/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /Chapter01/exercises/name/Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "name" 3 | version = "0.1.0" 4 | 5 | -------------------------------------------------------------------------------- /Chapter01/exercises/name/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "name" 3 | version = "0.1.0" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /Chapter01/exercises/name/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("John Smith"); 3 | } 4 | -------------------------------------------------------------------------------- /Chapter01/exercises/smallest_program.rs: -------------------------------------------------------------------------------- 1 | fn main() {} -------------------------------------------------------------------------------- /Chapter02/code/alias.rs: -------------------------------------------------------------------------------- 1 | type MagicPower = u16; 2 | 3 | fn main() { 4 | let mut run: MagicPower = 7800; 5 | run = 78000 6 | } -------------------------------------------------------------------------------- /Chapter02/code/bindings.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let energy = 5; // value 5 is bound to variable energy 3 | // splitting declaration and initialization: 4 | let energy2; 5 | energy2 = 5; 6 | let _energy = 5; // no warning unused variable 7 | // let energy = 5usize; // energy is now an unsigned integer 8 | let copy_energy = energy; 9 | println!("Your energy is {}", energy); 10 | let level_title = "Level 1"; 11 | let dead = false; 12 | let magic_number = 3.14f32; 13 | 14 | let energy = "Abundant"; // a new energy variable 15 | // an _ can be used to separate the digits from the type to improve readability: 16 | // let magic_number = 3.14_f32; 17 | let empty = (); // the value of the unit type () 18 | 19 | // changing values: 20 | // energy = 25; // error: re-assignment of immutable variable `energy` 21 | let mut fuel = 34; 22 | fuel = 60; 23 | 24 | let n; // error: type annotations needed, consider giving `energy2` a type, cannot infer type for `_` 25 | // println!("n is: {}", n); // error: use of possibly uninitialized variable 26 | n = -2; 27 | let n: i32; 28 | // let n: i32 = -2; // n is a binding of type i32 and with value -2 29 | let x = 42u8; 30 | let magic_number = 3.14f64; 31 | // fn2() // cannot find function `fn2` in this scope - not found in this scope 32 | } -------------------------------------------------------------------------------- /Chapter02/code/comments.rs: -------------------------------------------------------------------------------- 1 | /// Start of the Game 2 | fn main() { 3 | // Here starts the execution of the Game. 4 | // We begin with printing a welcome message: 5 | println!("Welcome to the Game!"); 6 | } -------------------------------------------------------------------------------- /Chapter02/code/constants1.rs: -------------------------------------------------------------------------------- 1 | use std::f32::consts; 2 | 3 | static MAX_HEALTH: i32 = 100; 4 | static GAME_NAME: &str = "Monster Attack"; 5 | 6 | fn main() { 7 | const MYPI: f32 = 3.14; 8 | println!("{}", MYPI); 9 | println!("{}", GAME_NAME); 10 | // use the PI value from the standard library: 11 | println!("{}", consts::PI); 12 | } 13 | 14 | // 3.14 15 | // Monster Attack 16 | // 3.141593 -------------------------------------------------------------------------------- /Chapter02/code/constants2.rs: -------------------------------------------------------------------------------- 1 | static MAX_HEALTH: i32 = 100; 2 | static GAME_NAME: &str = "Monster Attack"; 3 | 4 | fn main() { 5 | const MYPI: f32 = 3.14; 6 | 7 | println!("The Game you are playing is called {}.", GAME_NAME); 8 | println!("You start with {} health points.", MAX_HEALTH); 9 | println!("In the Game {0} you start with {1} % health, yes you read it correctly: {1} points!", 10 | GAME_NAME, MAX_HEALTH); 11 | println!("You have {points} % health", points = 70); 12 | 13 | // formatting: 14 | println!("MAX_HEALTH is {:x} in hexadecimal", MAX_HEALTH); 15 | println!("MAX_HEALTH is {:b} in binary", MAX_HEALTH); 16 | println!( "Two written in binary is {0:b}", 2); 17 | 18 | println!("pi is {:e} in floating point notation", MYPI); 19 | 20 | let long_decimal: f64 = 0.56545874854551248754; 21 | println!("{:.3}", long_decimal); // 0.565 22 | 23 | let number = 42i32; 24 | println!("{:08}", number); // 00000042 25 | println!("{:8}", number); // 42 26 | 27 | let str = format!("You have {points} % health", points = 70); 28 | println!("{}", str); // str now contains the value "You have 70 % health" 29 | } 30 | // The Game you are playing is called Monster Attack. 31 | // You start with 100 health points. 32 | // In the Game Monster Attack you start with 100 % health, yes you heard it correct: 100 points! 33 | // You have 70 % health 34 | // MAX_HEALTH is 64 in hexadecimal 35 | // MAX_HEALTH is 1100100 in binary 36 | // Two written in binary is 10 37 | // pi is 3.14e0 in floating point notation 38 | // 0.565 39 | // 00000042 40 | // 42 41 | // You have 70 % health -------------------------------------------------------------------------------- /Chapter02/code/expressions.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // declarative statements: 3 | let a = 2; 4 | let b = 5; 5 | let n = a + b; // n binds to 7 6 | let m: i8; 7 | 8 | m = 42; // expression that returns the unit value () 9 | 10 | // let p = q = 3; // unresolved name q 11 | 12 | // chained let bindings: 13 | let mut n = 0; 14 | let mut m = 1; 15 | let t = m; m = n; n = t; 16 | println!("{} {} {}", n, m, t); // 1 0 1 17 | 18 | // expression that returns a + b 19 | let n1 = { 20 | let a = 2; 21 | let b = 5; 22 | a + b // <-- no semicolon! 23 | }; 24 | println!("n1 is: {}", n1); // n1 is 7 25 | 26 | // expression that returns the unit value () 27 | let n2 = { 28 | let a = 2; 29 | let b = 5; 30 | a + b; 31 | }; 32 | println!("n2 is: {:?}", n2); // n2 is () 33 | } 34 | // 1 0 1 35 | // n1 is: 7 36 | // n2 is: () -------------------------------------------------------------------------------- /Chapter02/code/mutable_constant.rs: -------------------------------------------------------------------------------- 1 | static mut globvar: i32 = 42; 2 | 3 | fn main() { 4 | 5 | // error: use of mutable static requires unsafe function or block [E0133] 6 | unsafe { // because it is dangerous to change a global variable! 7 | globvar = 0; 8 | println!("My variable global constant: {}", globvar); 9 | } 10 | 11 | } 12 | // My variable global constant: 0 -------------------------------------------------------------------------------- /Chapter02/code/references.rs: -------------------------------------------------------------------------------- 1 | // #![feature(box_syntax)] // error: unstable feature in stable releases 2 | 3 | fn main() { 4 | let health = 32; 5 | let mut game = "Space Invaders"; 6 | println!("address of health-value: {:p}", &health); // prints 0x23fba4 7 | println!("address of game-value: {:p}", &game); // prints 0x23fb90 8 | println!("game-value: {}", game); // prints "Space Invaders" 9 | println!("game: {}", &game); // prints "Space Invaders" 10 | 11 | let game2 = &game; 12 | println!("{:p}", game2); // prints 0x23fb90 13 | println!("{}", *game2); // prints "Space Invaders" 14 | println!("{}", game2); // prints "Space Invaders" 15 | 16 | let x: &i64; 17 | // println!("{:?}", x); // error: use of possibly uninitialized variable: `x` 18 | 19 | // health = 33; // error: re-assignment of immutable variable `health` 20 | let y = &health; 21 | println!("{:}", *y); // 32 22 | 23 | // references to an immutable variable: 24 | let tricks = 10; 25 | // let reftricks = &mut tricks; // error: cannot borrow immutable local variable `tricks` as mutable 26 | 27 | // references to a mutable variable: 28 | let mut score = 0; 29 | let score2 = &score; 30 | //*score2 = 5; // cannot assign to immutable borrowed content *score2 31 | 32 | let mut score = 0; 33 | let score3 = &mut score; 34 | *score3 = 5; 35 | 36 | // let score4 = &mut score; 37 | // error: cannot borrow `score` as mutable more than once at a time 38 | 39 | // boxing values onto the heap: 40 | let x = Box::new(5i32); 41 | // let y = box 6; // error: box expression syntax is experimental; you can call `Box::new` instead. 42 | // or use feature gate #![feature(box_syntax)] 43 | // let x = box 5i32; 44 | 45 | } 46 | // address of health-value: 0x23fb04 47 | // address of game-value: 0x23faf0 48 | // game-value: Space Invaders 49 | // game: Space Invaders 50 | // 0x23faf0 51 | // Space Invaders 52 | // Space Invaders 53 | // 32 -------------------------------------------------------------------------------- /Chapter02/code/scope.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let outer = 42; 3 | { // start code block 4 | // This variable inner only exists in this block 5 | let inner = 3.14; 6 | println!("block variable: {}", inner); 7 | let outer = 99; // shadows the first outer variable 8 | println!("block variable outer: {}", outer); 9 | } // end of code block 10 | // println!("out of block: {}", inner); // error: unresolved name inner - not found in this scope 11 | println!("outer variable: {}", outer); 12 | } 13 | // block variable: 3.14 14 | // block variable outer: 99 15 | // outer variable: 42 -------------------------------------------------------------------------------- /Chapter02/code/test.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Using local inference, the compiler knows that `elem` has type u64 (machine-dependent) 3 | let elem = 42; 4 | // Create an empty vector (a growable array) 5 | let mut vec = Vec::new(); 6 | // At this point the compiler doesn't know the exact type of `vec`, it 7 | // just knows that it's a vector of something (`Vec<_>`) 8 | // Insert `elem` in the vector 9 | vec.push(elem); 10 | // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec`) 11 | // Try commenting out the `vec.push(elem)` line 12 | // --> error: unable to infer enough type information about `_`; type annotations required [E0282] 13 | println!("{:?}", vec); 14 | } 15 | // [42] 16 | -------------------------------------------------------------------------------- /Chapter02/code/type_conversions.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let points = 10i32; 3 | let mut saved_points: u32 = 0; 4 | // saved_points = points; // error 5 | // error: mismatched types: expected u32, found i32 6 | saved_points = points as u32; 7 | 8 | let f2 = 3.14; 9 | // truncation occurs here: 10 | saved_points = f2 as u32; 11 | println! ("{}", saved_points); // 3 12 | 13 | let mag = "Gandalf"; 14 | // saved_points = mag as u32; // error: non-scalar cast: `&str` as `u32` 15 | } -------------------------------------------------------------------------------- /Chapter02/code/type_errors.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let score: i32 = 100; 3 | // score = 50; // re-assignment of immutable variable 4 | // score = "YOU WON!"; 5 | // error: mismatched types: expected i32, found reference - expected `i32`, found `&'static str` 6 | let score = "YOU WON!"; 7 | 8 | let player1 = "Rob"; 9 | let player2 = "Jane"; 10 | // let player3 = player1 + player2; 11 | // error: binary operation `+` cannot be applied to type `&str` 12 | let player3 = player1.to_string() + player2; 13 | println!("{}", player3); 14 | let player3 = format!("{}{}", player1, player2); 15 | println!("{}", player3); 16 | } 17 | // RobJane 18 | // RobJane -------------------------------------------------------------------------------- /Chapter02/code/types2.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x = 42u8; 3 | let magic_number = 3.14f64; 4 | } -------------------------------------------------------------------------------- /Chapter02/exercises/change_constant.rs: -------------------------------------------------------------------------------- 1 | static MAXHEALTH: i32 = 100; 2 | static GAMENAME: &str = "Monster Attack"; 3 | 4 | fn main() { 5 | // MAXHEALTH = 99; // error: cannot assign to immutable static item 6 | } 7 | /*change_constant.rs:5:2: 5:16 error: cannot assign to immutable static item 8 | change_constant.rs:5 MAXHEALTH = 99; 9 | error: aborting due to previous error 10 | [Finished in 0.8s]*/ 11 | -------------------------------------------------------------------------------- /Chapter02/exercises/compound_let.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut a = 5; 3 | let mut b = 6; 4 | let n = 7; 5 | 6 | let a = b = n; 7 | println!("{:?}{:?}{:?}", a, b, n); // ()77 8 | 9 | // no swap : 10 | let mut c = 5; 11 | let mut d = 6; 12 | let c = d = c; 13 | println!("{:?}{:?}", c, d); // ()5 14 | } 15 | // a gets the value of the expression: b = n; 16 | // the value of that expression is () 17 | // ()77 18 | // ()5 -------------------------------------------------------------------------------- /Chapter02/exercises/formatting.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let dec = 3.2f32; 3 | // should be printed out as +003.20 4 | println!("{}", dec); // 3.2 5 | println!("{:+007.2}", dec); // +003.20 6 | // explanation: 7 | // +00 = literal text 8 | // 7 = total character width of output 9 | // .2 = 2 digits after decimal point 10 | } -------------------------------------------------------------------------------- /Chapter03/code/attributes_cfg.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | on_windows(); 3 | } 4 | 5 | #[cfg(target_os = "windows")] 6 | fn on_windows() { 7 | println!("This machine has Windows as its OS.") 8 | } 9 | // This machine has Windows as its OS. -------------------------------------------------------------------------------- /Chapter03/code/attributes_testing.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("No tests are compiled, compile with rustc --test!"); 3 | double(42); 4 | } 5 | 6 | pub fn double(n: i32) -> i32 { 7 | n * 2 8 | } 9 | 10 | #[test] 11 | fn arithmetic() { 12 | // good tests: 13 | // assert_eq!(actual, expected) 14 | assert_eq!(5, 2 + 3); 15 | assert_eq!(double(42), 84); 16 | assert!(2 + 3 == 5); 17 | // bad tests: 18 | if 2 + 3 == 5 { 19 | println!("You can calculate!"); 20 | } 21 | if 2 + 3 == 6 { // this test passes as wel! 22 | println!("You cannot calculate!"); 23 | } 24 | } 25 | 26 | #[test] 27 | fn badtest() { 28 | assert_eq!(6, 2 + 3); 29 | } 30 | 31 | #[test] 32 | #[should_panic(expected = "assertion failed")] 33 | fn failing_test() { 34 | assert!(6 == 2 + 3); 35 | } -------------------------------------------------------------------------------- /Chapter03/code/cube/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Chapter03/code/cube/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cube" 3 | version = "0.0.1" 4 | authors = ["Ivo Balbaert "] 5 | -------------------------------------------------------------------------------- /Chapter03/code/cube/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn cube(val: u32) -> u32 { 2 | val * val * val 3 | } 4 | 5 | #[cfg(test)] 6 | mod tests; 7 | 8 | -------------------------------------------------------------------------------- /Chapter03/code/cube/src/tests.rs: -------------------------------------------------------------------------------- 1 | // test module in a different file test.rs: 2 | use super::*; 3 | 4 | #[test] 5 | fn cube_of_2_is_8() { 6 | assert_eq!(cube(2), 8); 7 | } 8 | 9 | // other test functions: 10 | // ... -------------------------------------------------------------------------------- /Chapter03/code/cube/tests/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate cube; 2 | use cube::cube; 3 | 4 | #[test] 5 | fn cube_of_4_is_64() { 6 | assert_eq!(cube(4), 64); 7 | } 8 | 9 | // other test functions: 10 | // ... -------------------------------------------------------------------------------- /Chapter03/code/doc/.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/.lock -------------------------------------------------------------------------------- /Chapter03/code/doc/COPYRIGHT.txt: -------------------------------------------------------------------------------- 1 | These documentation pages include resources by third parties. This copyright 2 | file applies only to those resources. The following third party resources are 3 | included, and carry their own copyright notices and license terms: 4 | 5 | * Fira Sans (FiraSans-Regular.woff, FiraSans-Medium.woff): 6 | 7 | Copyright (c) 2014, Mozilla Foundation https://mozilla.org/ 8 | with Reserved Font Name Fira Sans. 9 | 10 | Copyright (c) 2014, Telefonica S.A. 11 | 12 | Licensed under the SIL Open Font License, Version 1.1. 13 | See FiraSans-LICENSE.txt. 14 | 15 | * Heuristica (Heuristica-Italic.woff): 16 | 17 | Copyright 1989, 1991 Adobe Systems Incorporated. All rights reserved. 18 | Utopia is either a registered trademark or trademark of Adobe Systems 19 | Incorporated in the United States and/or other countries. Used under 20 | license. 21 | 22 | Copyright 2006 Han The Thanh, Vntopia font family, http://vntex.sf.net 23 | 24 | Copyright (c) 2008-2012, Andrey V. Panov (panov@canopus.iacp.dvo.ru), 25 | with Reserved Font Name Heuristica. 26 | 27 | Licensed under the SIL Open Font License, Version 1.1. 28 | See Heuristica-LICENSE.txt. 29 | 30 | * jQuery (jquery-2.1.4.min.js): 31 | 32 | Copyright 2005, 2015 jQuery Foundation, Inc. 33 | Licensed under the MIT license (see LICENSE-MIT.txt). 34 | 35 | * rustdoc.css, main.js, and playpen.js: 36 | 37 | Copyright 2015 The Rust Developers. 38 | Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE.txt) or 39 | the MIT license (LICENSE-MIT.txt) at your option. 40 | 41 | * normalize.css: 42 | 43 | Copyright (c) Nicolas Gallagher and Jonathan Neal. 44 | Licensed under the MIT license (see LICENSE-MIT.txt). 45 | 46 | * Source Code Pro (SourceCodePro-Regular.woff, SourceCodePro-Semibold.woff): 47 | 48 | Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), 49 | with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark 50 | of Adobe Systems Incorporated in the United States and/or other countries. 51 | 52 | Licensed under the SIL Open Font License, Version 1.1. 53 | See SourceCodePro-LICENSE.txt. 54 | 55 | * Source Serif Pro (SourceSerifPro-Regular.woff, SourceSerifPro-Bold.woff): 56 | 57 | Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/), with 58 | Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of 59 | Adobe Systems Incorporated in the United States and/or other countries. 60 | 61 | Licensed under the SIL Open Font License, Version 1.1. 62 | See SourceSerifPro-LICENSE.txt. 63 | 64 | This copyright file is intended to be distributed with rustdoc output. 65 | -------------------------------------------------------------------------------- /Chapter03/code/doc/FiraSans-Medium.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/FiraSans-Medium.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/FiraSans-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/FiraSans-Regular.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/Heuristica-Italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/Heuristica-Italic.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /Chapter03/code/doc/SourceCodePro-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/SourceCodePro-Regular.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/SourceCodePro-Semibold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/SourceCodePro-Semibold.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/SourceSerifPro-Bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/SourceSerifPro-Bold.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/SourceSerifPro-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter03/code/doc/SourceSerifPro-Regular.woff -------------------------------------------------------------------------------- /Chapter03/code/doc/exdoc/cube.v.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Redirecting to fn.cube.html...

8 | 9 | 10 | -------------------------------------------------------------------------------- /Chapter03/code/doc/exdoc/sidebar-items.js: -------------------------------------------------------------------------------- 1 | initSidebarItems({"fn":[["cube","Calculates the cube `val * val * val`."]]}); -------------------------------------------------------------------------------- /Chapter03/code/doc/normalize.css: -------------------------------------------------------------------------------- 1 | /*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:bold}table{border-collapse:collapse;border-spacing:0}td,th{padding:0} 2 | -------------------------------------------------------------------------------- /Chapter03/code/doc/search-index.js: -------------------------------------------------------------------------------- 1 | var searchIndex = {}; 2 | searchIndex["exdoc"] = {"doc":"","items":[[5,"cube","exdoc","Calculates the cube `val * val * val`.",null,{"inputs":[{"name":"u32"}],"output":{"name":"u32"}}]],"paths":[]}; 3 | initSearch(searchIndex); 4 | -------------------------------------------------------------------------------- /Chapter03/code/exdoc.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("The cube of 4 is {}", cube(4)); 3 | } 4 | 5 | /// Calculates the cube `val * val * val`. 6 | /// 7 | /// # Examples 8 | /// 9 | /// ``` 10 | /// let cube = cube(val); 11 | /// ``` 12 | pub fn cube(val: u32) -> u32 { 13 | // implementation goes here 14 | val * val * val 15 | } 16 | // The cube of 4 is 64 -------------------------------------------------------------------------------- /Chapter03/code/fib_procedural.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let ans = fib(10); 3 | println!("{}", ans); 4 | } 5 | 6 | fn fib(x: i64) -> i64 { 7 | if x == 0 || x == 1 { return x; } 8 | fib(x - 1) + fib(x - 2) 9 | } 10 | // 55 -------------------------------------------------------------------------------- /Chapter03/code/functions.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let hero1 = "Pac Man"; // is of type &str 3 | let hero2 = "Riddick"; 4 | greet(hero2); 5 | greet_both(hero1, hero2); 6 | 7 | let power = increment_power(1); 8 | println!("I am now at power level: {}", power); 9 | assert_eq!(2, power); 10 | 11 | println!("{}", double_input(4)); 12 | println!("{}", double_inputs(4)); 13 | } 14 | 15 | fn greet(name: &str) { 16 | println!("Hi mighty {}, what brings you here?", name); 17 | } 18 | 19 | fn greet_both(name1: &str, name2: &str) { 20 | greet(name1); 21 | greet(name2); 22 | } 23 | 24 | fn increment_power(power: i32) -> i32 { 25 | // if power < 100 { return 999 } 26 | println!("My power is going to increase:"); 27 | // power + 1; // results in: error[E0308]: mismatched types - not all control paths return a value 28 | // return power + 1 // poor style 29 | power + 1 30 | } 31 | 32 | fn double_input(mut i: u32) -> u32 { 33 | i = i * 2; 34 | i 35 | } 36 | 37 | // no need for a temporary mut variable: 38 | fn double_inputs(i: u32) -> u32 { i * 2 } 39 | 40 | // Hi mighty Riddick, what brings you here? 41 | // Hi mighty Pac Man, what brings you here? 42 | // Hi mighty Riddick, what brings you here? 43 | // My power is going to increase: 44 | // I am now at power level: 2 45 | // 8 46 | // 8 47 | -------------------------------------------------------------------------------- /Chapter03/code/ifelse.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let dead = false; 3 | let health = 48; 4 | 5 | if dead { 6 | println!("Game over!"); 7 | return; 8 | } 9 | 10 | if dead { 11 | println!("Game over!"); 12 | return; 13 | } else { 14 | println!("You still have a chance to win!"); 15 | } 16 | 17 | if health >= 50 { 18 | println!("Continue to fight!"); 19 | } else if health >= 20 { 20 | println!("Stop the battle and gain strength!"); 21 | } else { 22 | println!("Hide and try to recover!"); 23 | } 24 | 25 | let active = if health >= 50 { 26 | true 27 | } else { 28 | false 29 | }; 30 | println!("Am I active? {}", active); 31 | 32 | // alternative for ternary operator: 33 | let adult = true; 34 | let age = if adult { "+18" } else { "-18" }; 35 | println!("Age is {}", age); 36 | } 37 | // Stop the battle and gain strength! 38 | // Am I active? false 39 | // Age is +18 -------------------------------------------------------------------------------- /Chapter03/code/loops.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // while loop: 3 | let max_power = 10; 4 | let mut power = 1; 5 | while power < max_power { 6 | print!("{} ", power); // prints without newline 7 | power += 1; // increment counter 8 | } 9 | println!(""); 10 | 11 | // infinite loop with continue and break: 12 | println!("I gain Infinite power!"); 13 | loop { 14 | power += 1; 15 | if power == 42 { 16 | // Skip the rest of this iteration 17 | continue; 18 | } 19 | print!("{} ", power); 20 | if power == 50 { 21 | print!("OK, that's enough for today"); 22 | break; // exit the loop 23 | } 24 | } 25 | 26 | println!(""); 27 | // use of labels: 28 | 'outer: loop { 29 | println!("Entered the outer dungeon."); 30 | 'inner: loop { 31 | println!("Entered the inner dungeon."); 32 | // break; // breaks only from the inner loop 33 | break 'outer; // breaks to the outer loop 34 | } 35 | // error: unreachable statement 36 | // println!("This treasure can sadly never be reached."); 37 | } 38 | println!("Exited the outer dungeon!"); 39 | 40 | // for in loop: 41 | for n in 1..11 { 42 | println!("The square of {} is {}", n, n * n); 43 | } 44 | 45 | let mut x = 10; 46 | for _ in 1..x { x -= 1; print!("."); } 47 | 48 | } 49 | // 1 2 3 4 5 6 7 8 9 50 | // I gain Infinite power! 51 | // 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 43 44 45 46 47 48 49 50 52 | // OK, that's enough for today 53 | // Entered the outer dungeon. 54 | // Entered the inner dungeon. 55 | // Exited the outer dungeon! 56 | // The square of 1 is 1 57 | // The square of 2 is 4 58 | // The square of 3 is 9 59 | // The square of 4 is 16 60 | // The square of 5 is 25 61 | // The square of 6 is 36 62 | // The square of 7 is 49 63 | // The square of 8 is 64 64 | // The square of 9 is 81 65 | // The square of 10 is 100 66 | // ......... -------------------------------------------------------------------------------- /Chapter03/code/mylib/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Chapter03/code/mylib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mylib" 3 | version = "0.1.0" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /Chapter03/code/mylib/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(not(test))] 2 | fn main() { 3 | println!("Normal mode, no test was compiled"); 4 | } 5 | 6 | pub fn double(n: i32) -> i32 { 7 | n * 2 8 | } 9 | 10 | #[cfg(test)] 11 | mod tests { 12 | use super::*; 13 | 14 | #[test] 15 | fn it_works() { 16 | assert_eq!(double(42), 84); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter03/code/nested_function.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | foo(); 3 | } 4 | 5 | fn foo() { 6 | fn bar() { println!("bar"); } 7 | bar(); 8 | } 9 | // bar 10 | -------------------------------------------------------------------------------- /Chapter03/exercises/absolute.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(5, abs(-5)); 3 | } 4 | 5 | // error version: 6 | // fn abs(x: i32) -> u32 { 7 | // if x > 0 { x } 8 | // else { -x } 9 | // } 10 | // lines 6 and 7: 11 | // error[E0308]: mismatched types: expected u32, found i32 12 | 13 | // corrected version: 14 | fn abs(x: i32) -> i32 { 15 | if x > 0 { 16 | x 17 | } else { 18 | -x 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter03/exercises/ifreturn.rs: -------------------------------------------------------------------------------- 1 | fn verbose(x: i32) -> &'static str { 2 | let result: &'static str; 3 | if x < 10 { 4 | result = "less than 10"; 5 | } else { 6 | result = "10 or more"; 7 | } 8 | return result; 9 | } 10 | 11 | fn simple(x: i32) -> &'static str { 12 | if x < 10 { "less than 10" } 13 | else { "10 or more" } 14 | } 15 | 16 | fn main() { 17 | let n = 13; 18 | println!("verbose: {}", verbose(n)); 19 | println!("simple: {}", simple(n)); 20 | } 21 | // verbose: 10 or more 22 | // simple: 10 or more 23 | -------------------------------------------------------------------------------- /Chapter03/exercises/iftest.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // 1) ; after expressions: 3 | let adult = true; 4 | let age = if adult { "+18"; } else { "-18"; }; 5 | println!("Age is {:?}", age); // Age is () 6 | // the following gives 7 | // error [E0308]: mismatched types: expected (), found &str 8 | // let age: &str = if adult { "+18"; } else { "-18"; }; 9 | 10 | // 2) block without { } ? 11 | // let n = 10; 12 | // if n > 5 println!("n is bigger than 5"); 13 | // error: expected `{`, found `println` 14 | // help: place this code inside a block 15 | 16 | // 3) block without { } ? 17 | let health = -3; 18 | let result = if health <=0 { "Game over man!" }; 19 | // error: if may be missing an else clause: 20 | // expected (), found &str 21 | // This doesn't work because the absence of the else part is viewed as else { () } 22 | // where () is a unit value of type (), which is not of type string 23 | // correction: 24 | let result = if health <=0 { "Game over man!" } else { "" }; 25 | } -------------------------------------------------------------------------------- /Chapter04/code/arguments.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | 3 | fn main() { 4 | // command-line arguments: 5 | let args: Vec = env::args().collect(); 6 | println!("The program's name is: {}", args[0]); 7 | for arg in args.iter() { 8 | println!("Next argument is: {}", arg) 9 | } 10 | println!("I got: {} arfguments", args.len() - 1); 11 | for n in 1..args.len() { 12 | println!("The {}th argument is {}", n, args[n]); 13 | } 14 | // slice pattern is experimental (see issue #23121) 15 | // match &args[..] { 16 | // [ref progname] => { no() }, // no arguments passed 17 | // [_, ref arg1] => { one() }, // one argument passed 18 | // [_, ref arg1, ref arg2] => { two() }, // two arguments passed 19 | // _ => { help(); } // all the other cases 20 | // } 21 | 22 | // OS-environment variables: 23 | let osvars = env::vars(); 24 | for (key, value) in osvars { 25 | println!("{}: {}", key, value); 26 | } 27 | } 28 | 29 | // fn no() { println!("no arguments");} 30 | // fn one() { println!("one argument");} 31 | // fn two() { println!("two arguments"); } 32 | 33 | // fn help() { 34 | // println!("Usage: 35 | // arguments Check whether string is ok. 36 | // arguments func1 Apply func1 to integer"); 37 | // } 38 | -------------------------------------------------------------------------------- /Chapter04/code/destructure_enum.rs: -------------------------------------------------------------------------------- 1 | use En::*; 2 | 3 | struct St { 4 | f1: i32, 5 | f2: f32 6 | } 7 | 8 | enum En { 9 | Var1, 10 | Var2, 11 | Var3(i32), 12 | Var4(i32, St, i32) 13 | } 14 | 15 | fn foo(x: En) { 16 | match x { 17 | Var1 => println!("first variant"), 18 | Var2 => println!("second variant"), 19 | Var3(..) => println!("third variant"), 20 | Var4(..) => println!("fourth variant") 21 | } 22 | } 23 | 24 | fn foo2(x: &En) { 25 | match x { 26 | &Var1 => println!("first variant"), 27 | &Var2 => println!("second variant"), 28 | &Var3(5) => println!("third variant with number 5"), 29 | &Var3(x) => println!("third variant with number {} (not 5)", x), 30 | &Var4(3, St{ f1: 3, f2: x }, 45) => { 31 | println!("destructuring an embedded struct, found {} in f2", x) 32 | } 33 | _ => println!("other (Var4)") 34 | // cannot move out of borrowed content: 35 | // &Var4(_, v, _) => { 36 | // println!("Some other Var4 with {} in f1 and {} in f2", v.f1, v.f2) 37 | // } 38 | // // _ => println!("other (Var2)") // unreachable pattern 39 | } 40 | } 41 | 42 | fn main() { 43 | let en1 = En::Var3(42); 44 | // foo(en1); // third variant 45 | foo2(&en1); // third variant with number 42 (not 5) 46 | let st1 = St { f1: 3, f2: 10.0 }; 47 | // let en2 = En::Var4(3, st1, 45); 48 | // foo2(&en2); // destructuring an embedded struct, found 10 in f2 49 | let en3 = En::Var4(3, st1, 42); 50 | foo2(&en3); // other (Var4) 51 | } 52 | // third variant with number 42 (not 5) 53 | // other (Var4) -------------------------------------------------------------------------------- /Chapter04/code/destructuring_structs.rs: -------------------------------------------------------------------------------- 1 | struct Big { 2 | field1: i32, 3 | field2: i32, 4 | field3: i32, 5 | field4: i32, 6 | field5: i32, 7 | field6: i32, 8 | field7: i32, 9 | field8: i32, 10 | field9: i32 11 | } 12 | 13 | fn foo(b: Big) { 14 | let Big { field6: x, field3: y, ..} = b; 15 | println!("pulled out {} and {}", x, y); 16 | let Big { field6, field3, ..} = b; 17 | println!("pulled out {} and {}", field3, field6); 18 | let Big { field3: ref x, ref field6, ..} = b; 19 | println!("pulled out {} and {}", *x, *field6); 20 | } 21 | 22 | fn main() { 23 | let big = Big {field1: 1, field2: 2, field3: 3, field4: 4, 24 | field5: 5, field6: 6, field7: 7, field8: 8, field9: 9}; 25 | foo(big); 26 | } 27 | // pulled out 6 and 3 28 | // pulled out 3 and 6 29 | // pulled out 3 and 6 -------------------------------------------------------------------------------- /Chapter04/code/enums.rs: -------------------------------------------------------------------------------- 1 | use PlanetaryMonster::MarsMonster; 2 | 3 | enum Compass { 4 | North, South, East, West 5 | } 6 | 7 | type species = &'static str; 8 | 9 | enum PlanetaryMonster { 10 | VenusMonster(species, i32), 11 | MarsMonster(species, i32) 12 | } 13 | 14 | fn main() { 15 | let direction = Compass::West; 16 | let martian = PlanetaryMonster::MarsMonster("Chela", 42); 17 | let martian = MarsMonster("Chela", 42); 18 | 19 | // using enum values: 20 | // error: binary operation `==` cannot be applied to type `Compass` 21 | // if direction == Compass::East { 22 | // println!("Go to the east"); 23 | // } 24 | 25 | match direction { 26 | Compass::North => println!("Go to the North!"), 27 | Compass::East => println!("Go to the East!"), 28 | Compass::South => println!("Go to the South!"), 29 | Compass::West => println!("Go to the West!"), 30 | } 31 | } 32 | // Go to the West! -------------------------------------------------------------------------------- /Chapter04/code/enums2.rs: -------------------------------------------------------------------------------- 1 | enum Color { 2 | Red, 3 | Green, 4 | Blue, 5 | RGB(i32, i32, i32) 6 | } 7 | 8 | enum Color2 { 9 | Red = 0xff0000, 10 | Green = 0x00ff00, 11 | Blue = 0x0000ff, 12 | } 13 | 14 | fn print_color(c: Color) { 15 | match c { 16 | Color::Red => println!("#ff0000"), 17 | Color::Green => println!("#00ff00"), 18 | Color::Blue => println!("#0000ff"), 19 | Color::RGB(r, g, b) => println!("#{:02x}{:02x}{:02x}", r, g, b) 20 | } 21 | } 22 | 23 | enum Day { // achterliggend discriminator vanaf 0 24 | Monday, 25 | Tuesday, 26 | Wednesday, 27 | Thursday, 28 | Friday, 29 | Saturday, 30 | Sunday, 31 | } 32 | 33 | 34 | impl Day { 35 | fn mood(&self) { 36 | println!("{}", match *self { 37 | Day::Friday => "it's friday!", 38 | Day::Saturday | Day::Sunday => "weekend :-)", 39 | _ => "weekday...", 40 | }) 41 | } 42 | } 43 | 44 | fn main() { 45 | print_color(Color::Red); 46 | print_color(Color::RGB(0x12, 0x45, 0xba)); 47 | 48 | // enums can be casted into integers 49 | println!("roses are #{:06x}", Color2::Red as i32); 50 | println!("violets are #{:06x}", Color2::Blue as i32); 51 | 52 | let today = Day::Monday; 53 | today.mood(); 54 | } 55 | // #ff0000 56 | // #1245ba 57 | // roses are #ff0000 58 | // violets are #0000ff 59 | // weekday... -------------------------------------------------------------------------------- /Chapter04/code/input.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn main() { 4 | println!("What's your name, noble warrior?"); 5 | let mut buf = String::new(); 6 | // version with .ok().expect(): 7 | // io::stdin().read_line(&mut buf) 8 | // .ok() 9 | // .expect("Failed to read line"); 10 | // let name = buf.trim(); 11 | // println!("{}, that's a mighty name indeed!", name); 12 | 13 | // version with unwrap(): 14 | // io::stdin().read_line(&mut buf).unwrap(); 15 | // let name = buf.trim(); 16 | // println!("{}, that's a mighty name indeed!", name); 17 | 18 | // alternative with testing is_ok(): 19 | if io::stdin().read_line(&mut buf).is_ok() { 20 | let name = buf.trim(); 21 | println!("{}, that's a mighty name indeed!", name); 22 | } 23 | else { 24 | println!("Failed to read line!"); 25 | } 26 | } 27 | // What's your name, noble warrior? 28 | // Riddick 29 | // Riddick, that's a mighty name indeed! 30 | 31 | -------------------------------------------------------------------------------- /Chapter04/code/match_tuple.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // let status = 7; 3 | // error: mismatched types: 4 | // expected `_`, found `(_, _)` (expected integral variable, found tuple) [E0308] 5 | 6 | // correction: 7 | // let status = ('a', false); 'a' is not an integer 8 | let status = (42, true); 9 | match status { 10 | (0, true) => println!("Success"), 11 | (_, true) => println!("Pyrrhic victory"), // Any first value matches 12 | (_, _) => println!("Complete loss") // Any pair of values will match 13 | } 14 | 15 | let x = (59, false); 16 | match x { 17 | (n, true) if (n >= 20 && n <= 26) => println!("true and between 20 and 26"), 18 | (20...26, true) => println!("true and between 20 and 26"), 19 | (n, true) if !(n >= 20 && n <= 26) => println!("true and not between 20 and 26"), 20 | (40...49, _) => println!("between 40 and 49"), 21 | (_, _) => println!("Everything else") 22 | } 23 | 24 | } 25 | // Pyrrhic victory 26 | // Everything else 27 | -------------------------------------------------------------------------------- /Chapter04/code/pattern_match.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn main() { 4 | print!("Give a secret positive number: "); 5 | let mut buf = String::new(); 6 | io::stdin().read_line(&mut buf) 7 | .ok() 8 | .expect("Failed to read number"); 9 | let input_num: Result = buf.trim().parse(); 10 | // alternative: 11 | // let input_num = buf.trim().parse::(); 12 | 13 | // println!("Unwrap found {}", input_num.unwrap()); 14 | 15 | match input_num { 16 | Ok(num) => println!("{}", num), 17 | Err(ex) => println!("Please input an integer number! {}", ex) 18 | }; 19 | 20 | // binding the value of a match: 21 | // let num = match input_num { 22 | // Ok(num) => num, 23 | // Err(_) => 0 24 | // }; 25 | 26 | let input_num: Result = buf.trim().parse(); 27 | // alternative way for destructuring the Result: 28 | if let Ok(val) = input_num { 29 | println!("Matched {:?}!", val); 30 | } else { 31 | println!("No match!"); 32 | } 33 | 34 | // while let Ok(val) = input_num { 35 | // println!("Matched {:?}!", val); 36 | // if val == 42 { break } 37 | // } 38 | } 39 | // Give a positive secret number: 42 40 | // 42 41 | // Matched 42! 42 | -------------------------------------------------------------------------------- /Chapter04/code/pattern_match2.rs: -------------------------------------------------------------------------------- 1 | struct Point { 2 | x: i32, 3 | y: i32 4 | } 5 | 6 | fn main() { 7 | // exhaustive match with _: 8 | let magician = "Gandalf"; 9 | match magician { 10 | "Gandalf" => println!("A good magician!"), 11 | "Sauron" => println!("A magician turned bad!"), 12 | _ => println!("No magician turned up!") 13 | } 14 | 15 | // matching several values in a branch: 16 | let magical_number: i32 = 42; 17 | match magical_number { 18 | // Match a single value 19 | 1 => println!("Unity!"), 20 | // Match several values 21 | 2 | 3 | 5 | 7 | 11 => println!("Ok, these are primes"), 22 | // Match an inclusive range 23 | // 40...42 => println!("It is contained in this range"), 24 | num @ 40...42 => println!("{} is contained in this range ", num), 25 | // Handle the rest of cases 26 | _ => println!("No magic at all!"), 27 | } 28 | 29 | // destructuring a tuple: 30 | // see also match_tuple.rs 31 | // destructuring values and using guards: 32 | let loki = ("Loki", true, 800u32); 33 | match loki { 34 | (name, demi, _) if demi => { 35 | print!("This is a demigod "); 36 | println!("called {}", name); 37 | } 38 | (name, _, _) if name == "Thor" => println!("This is Thor!"), 39 | (_, _, pow) if pow <= 1000 => println!("This is a powerless god"), 40 | _ => println!("This is something else") 41 | } 42 | 43 | // destructuring a struct: 44 | let origin = Point { x: 0, y: 0 }; 45 | match origin { 46 | Point { x: x, y: y } => println!("This is the point: ({},{})", x, y), 47 | } 48 | 49 | // matching on a pointer: 50 | let x = &5; 51 | match x { 52 | &val => println!("Got a pointer value: {}", val), 53 | } 54 | 55 | } 56 | // A good magician! 57 | // 42 is contained in this range 58 | // This is a demigod called Loki 59 | // This is the point: (0,0) 60 | // Got a pointer value: 5 -------------------------------------------------------------------------------- /Chapter04/code/remove_elem_vector.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut vec1: Vec = (0..10).collect(); 3 | vec1.retain(|&x| !is_odd(x)); 4 | println!("{:?}", vec1) 5 | } 6 | 7 | fn is_odd(n: i32) -> bool { n % 2 != 0 } 8 | // [0, 2, 4, 6, 8] -------------------------------------------------------------------------------- /Chapter04/code/structs.rs: -------------------------------------------------------------------------------- 1 | struct Player { 2 | nname: &'static str, // nickname 3 | health: i32, 4 | level: u8 5 | } 6 | 7 | fn main() { 8 | struct Scoreu; // unit struct 9 | 10 | // tuple structs: 11 | struct Score(i32, u8); 12 | let score1 = Score(73, 2); // make (instantiate) a tuple struct 13 | let Score(h, l) = score1; // // extract values by destructuring 14 | println!("Health {} - Level {}", h, l); 15 | 16 | // newtype: 17 | struct Kilograms(u32); 18 | let weight = Kilograms(250); 19 | let Kilograms(kgm) = weight; // extracting kgm 20 | println!("weight is {} kilograms", kgm); 21 | 22 | // struct: 23 | let mut pl1 = Player{ nname: "Dzenan", health: 73, level: 2 }; 24 | println!("Player 1 {} is at level {}", pl1.nname, pl1.level); 25 | pl1.level = 3; 26 | 27 | // update syntax: 28 | let pl2 = Player{ nname: "Ivo", ..pl1 }; 29 | println!("Player 2 {} is at level {}", pl2.nname, pl2.level); 30 | 31 | // destructuring a struct: 32 | let Player{ health: ht, nname: nn, .. } = pl1; 33 | println!("Player {} has health {}", nn, ht); 34 | 35 | // pointers do automatic dereferencing when accessing data structure elements: 36 | let ps = &Player{ nname: "John", health: 95, level: 1 }; 37 | println!("{} == {}", ps.nname, (*ps).nname); 38 | } 39 | // Health 73 - Level 2 40 | // weight is 250 kilograms 41 | // Player 1 Dzenan is at level 2 42 | // Player 2 Ivo is at level 3 43 | // Player Dzenan has health 73 44 | // John == John -------------------------------------------------------------------------------- /Chapter04/code/tuples.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let thor = ("Thor", true, 3500u32); 3 | println!("{:?}", thor); // ("Thor", true, 3500) 4 | // type of thor: (&str, bool, u32) 5 | println!("{} - {} - {}", thor.0, thor.1, thor.2); 6 | 7 | // destructuring: 8 | let (name, _, power) = thor; 9 | println!("{} has {} power points", name, power); 10 | 11 | // one-element tuple: 12 | let one = (1,); 13 | 14 | // function returning a tuple and destructuring the return value: 15 | let (god, strength) = increase_power(thor.0, thor.2); 16 | println!("This god {} has now strength {} ", god, strength); 17 | 18 | let pair_thor = (thor.0, thor.2); 19 | let (god, strength) = increase_power2(pair_thor); 20 | println!("This god {} has now strength {} ", god, strength); 21 | 22 | // swapping variables with a tuple: 23 | let mut n = 0; 24 | let mut m = 1; 25 | let (n, m) = (m, n); 26 | println!("n: {} m: {}", n, m); 27 | } 28 | 29 | fn increase_power(name: &str, power: u32) -> (&str, u32) { 30 | if power > 1000 { 31 | (name, power * 3) 32 | } else { 33 | (name, power * 2) 34 | } 35 | } 36 | 37 | fn increase_power2((name, power): (&str, u32)) -> (&str, u32) { 38 | if power > 1000 { 39 | (name, power * 3) 40 | } else { 41 | (name, power * 2) 42 | } 43 | } 44 | 45 | // ("Thor", true, 3500) 46 | // Thor - true - 3500 47 | // Thor has 3500 power points 48 | // This god Thor has now strength 10500 49 | // This god Thor has now strength 10500 50 | // n: 1 m: 0 -------------------------------------------------------------------------------- /Chapter04/exercises/chars_string.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let magician = "Merlin"; 3 | // does not compile: 4 | // error: the trait `core::ops::Index<_>` is not implemented 5 | // for the type `collections::string::String` [E0277] 6 | // in Unicode: each character can be a variable number of bytes 7 | // println!("{}", (magician.to_string())[0]); 8 | let mut str = String::new(); 9 | str.push_str("Gandalf"); 10 | // does not compile: 11 | // error: the trait `core::ops::Index<_>` is not implemented 12 | // for the type `collections::string::String` [E0277] 13 | // in Unicode: each character can be a variable number of bytes 14 | // println!("{}", str[3]); 15 | 16 | // solution: use an iterator: 17 | let greeting = "Hello, 世界!"; 18 | println!("Bytes:"); 19 | for c in greeting.bytes() { // same as as_bytes() 20 | print!("{} - ", c); 21 | } 22 | println!(""); 23 | println!("Chars:"); 24 | for c in greeting.chars() { 25 | print!("{} - ", c); 26 | } 27 | } 28 | // Bytes: 29 | // 72 - 101 - 108 - 108 - 111 - 44 - 32 - 228 - 184 - 150 - 231 - 149 - 140 - 33 - 30 | // Chars: 31 | // H - e - l - l - o - , - - 世 - 界 - ! - -------------------------------------------------------------------------------- /Chapter04/exercises/match_type.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // let status = 7; 3 | // error: mismatched types: 4 | // expected `_`, found `(_, _)` (expected integral variable, found tuple) [E0308] 5 | 6 | // correction: 7 | // let status = ('a', false); 'a' is not an integer 8 | let status = (42, true); 9 | match status { 10 | (0, true) => println!("Success"), 11 | (_, true) => println!("Pyrrhic victory"), // Any first value matches 12 | (_, _) => println!("Complete loss") // Any pair of values will match 13 | } 14 | } 15 | // Pyrrhic victory 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter04/exercises/matching.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let x = (59, false); 3 | 4 | match x { 5 | // (n, true) if (n >= 20 && n <= 26) => println!("true and between 20 and 26"), 6 | (20...26, true) => println!("true and between 20 and 26"), 7 | (n, true) if !(n >= 20 && n <= 26) => println!("true and not between 20 and 26"), 8 | (40...49, _) => println!("between 40 and 49"), 9 | (_, _) => println!("Everything else") 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter04/exercises/monster.rs: -------------------------------------------------------------------------------- 1 | struct Monster { 2 | health: i32, 3 | damage: i32 4 | } 5 | 6 | fn main() { 7 | let m = Monster { health: 10, damage: 20 }; 8 | 9 | println!("{}", m.health); 10 | println!("{}", m.damage); 11 | } 12 | // 10 13 | // 20 -------------------------------------------------------------------------------- /Chapter04/exercises/pattern_match.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // exhaustive match with _: 3 | let magician = "Gandalf"; 4 | match magician { 5 | "Gandalf" => println!("A good magician!"), 6 | _ => println!("No magician turned up!"), 7 | // "Sauron" => println!("A magician turned bad!") // error: unreachable pattern [E0001] 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/exercises/tuples_ex.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // (2, 'a') == (5, false); 3 | // error: mismatched types: expected `char`, found `bool` (expected char, found bool) 4 | 5 | // mutability of tuples: 6 | let thor = (4, 5.0, false, "hello"); 7 | println!("{} - {} - {}", thor.0, thor.1, thor.2); 8 | // thor.0 = 42; // error: cannot assign to immutable anonymous field `thor.0` 9 | 10 | let mut thor = (4, 5.0, false, "hello"); 11 | println!("{} - {} - {}", thor.0, thor.1, thor.2); 12 | thor.0 = 42; // ok! 13 | println!("{} - {} - {}", thor.0, thor.1, thor.2); 14 | 15 | let empty_tup = (); 16 | if () == () { 17 | println!("The unit value is an empty tuple"); 18 | } 19 | } 20 | // 4 - 5 - false 21 | // 4 - 5 - false 22 | // 42 - 5 - false 23 | // The unit value is an empty tuple -------------------------------------------------------------------------------- /Chapter05/code/adapters_consumers.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // CONSUMERS: 3 | println!("CONSUMERS: "); 4 | // collect: 5 | let rng = 0..1000; 6 | let rngvec: Vec = rng.collect(); 7 | // alternative: 8 | // let rngvec = rng.collect::>(); 9 | println!("{:?}", rngvec); 10 | 11 | // find: 12 | let mut rng = 0..1000; 13 | let forty_two = rng.find(|n| *n >= 42); 14 | println!("{:?}", forty_two); // Some(42) 15 | // find needs a mutable variable, and moves it 16 | 17 | // ADAPTERS: 18 | // filter: 19 | println!("ADAPTERS: "); 20 | println!("FILTER:"); 21 | rng = 0..1000; 22 | let rng_even = rng.filter(|n| is_even(*n)) 23 | .collect::>(); 24 | println!("{:?}", rng_even); 25 | 26 | // alternative without collect: 27 | let rng = 1..100; 28 | let rng_even = rng.filter(|n| is_even(*n)); 29 | for x in rng_even { 30 | println!("{}", x); 31 | } 32 | 33 | // map: 34 | println!("MAP:"); 35 | let rng = 0..1000; 36 | let rng_even_pow3 = rng.filter(|n| is_even(*n)) 37 | .map(|n| n * n * n) 38 | .collect::>(); 39 | println!("{:?}", rng_even_pow3); 40 | println!("TAKE:"); 41 | let rng = 0..1000; 42 | let rng_even_pow3_first5 = rng.filter(|n| is_even(*n)) 43 | .map(|n| n * n * n) 44 | .take(5) 45 | .collect::>(); 46 | println!("{:?}", rng_even_pow3_first5); 47 | } 48 | 49 | fn is_even(n: i32) -> bool { 50 | n % 2 == 0 51 | } 52 | // CONSUMERS: 53 | // [0, 1, 2, 3, 4, ..., 999 ] 54 | // Some(42) 55 | // ADAPTERS: 56 | // FILTER: 57 | // [0, 2, 4, ..., 996, 998] 58 | // MAP: 59 | // [0, 8, 64, ..., 988047936, 994011992] 60 | // TAKE: 61 | // [0, 8, 64, 216, 512] -------------------------------------------------------------------------------- /Chapter05/code/dispatch.rs: -------------------------------------------------------------------------------- 1 | struct Circle; 2 | struct Triangle; 3 | 4 | trait Figure { 5 | fn print(&self); 6 | } 7 | 8 | impl Figure for Circle { 9 | fn print(&self) { 10 | println!("Circle"); 11 | } 12 | } 13 | 14 | impl Figure for Triangle { 15 | fn print(&self) { 16 | println!("Triangle"); 17 | } 18 | } 19 | 20 | // static dispatch 21 | fn log(figure: &T) { 22 | figure.print(); 23 | } 24 | 25 | // dynamic dispatch: function takes a trait object 26 | fn logd(figure: &Figure) { 27 | figure.print(); 28 | } 29 | 30 | fn main() { 31 | // static dispatch 32 | let circle = Circle; 33 | let triangle = Triangle; 34 | 35 | log(&circle); 36 | log(&triangle); 37 | 38 | // dynamic dispatch: 39 | let mut figures: Vec> = Vec::new(); 40 | figures.push(Box::new(Circle)); 41 | figures.push(Box::new(Triangle)); 42 | 43 | // the precise type of figure can only be known at runtime: 44 | for figure in figures { 45 | // log(&*figure); // error: the trait `core::marker::Sized` is not implemented for the type `Figure` 46 | logd(&*figure); 47 | } 48 | } 49 | // Circle 50 | // Triangle 51 | // Circle 52 | // Triangle -------------------------------------------------------------------------------- /Chapter05/code/error_div.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // panics: 3 | let x = 3; 4 | let y = 0; 5 | x / y; // thread '
' panicked at 'attempted to divide by zero' 6 | } 7 | -------------------------------------------------------------------------------- /Chapter05/code/errors.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // panics: 3 | let x = 3; 4 | // let y = 0; 5 | let y = 3; 6 | // x / y; // thread '
' panicked at 'attempted to divide by zero' 7 | // if y == 0 { panic!("Division by 0 occurred, exiting"); } 8 | println!("{}", div(x, y)); // returns 1 if y = 3 9 | 10 | // assert!(x == 5); // thread '
' panicked at 'assertion failed: x == 5' 11 | // assert_eq!(x, 5); // thread '
' panicked at 'assertion failed: (left: `3`, right: `5`)', 12 | // unreachable!(); // thread '
' panicked at 'internal error: entered unreachable code' 13 | } 14 | 15 | fn div(x: i32, y: i32) -> f32 { 16 | // if y == 0 { panic!("Division by 0 occurred, exiting"); } 17 | assert!(y != 0, "Division by 0 occurred, exiting"); 18 | (x / y) as f32 19 | } -------------------------------------------------------------------------------- /Chapter05/code/generics.rs: -------------------------------------------------------------------------------- 1 | use std::f32; 2 | 3 | struct Person { 4 | name: &'static str, 5 | id: i32 6 | } 7 | 8 | struct Pair { 9 | first: T, 10 | second: T, 11 | } 12 | 13 | fn main() { 14 | // generic structs: 15 | let magic_pair: Pair = Pair { first: 7, second: 42 }; 16 | let pair_of_magicians: Pair<&str> = Pair { first: "Gandalf", second: "Sauron" }; 17 | let a = second(magic_pair); 18 | 19 | // using Option 20 | let x: Option = Some(5); 21 | let pi: Option = Some(3.14159265359); 22 | let none: Option = None; 23 | let none2 = None::; 24 | let name: Option<&str> = Some("Joyce"); 25 | // let magic: Option = Some(42); // error: mismatched types 26 | 27 | let p1 = Person{ name: "James Bond", id: 7 }; 28 | let p2 = Person{ name: "Vin Diesel", id: 12 }; 29 | let p3 = Person{ name: "Robin Hood", id: 42 }; 30 | let op1: Option = Some(p1); 31 | let pvec: Vec = vec![p2, p3]; // type annotation is not necessary 32 | // let pvec = vec![p2, p3]; 33 | } 34 | 35 | fn second(pair: Pair) { 36 | pair.second; 37 | } 38 | -------------------------------------------------------------------------------- /Chapter05/code/higher_functions.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut strength = 26; 3 | println!("My tripled strength equals {}", triples(strength) ); // 78 4 | println!("My strength is still {}", strength); // 26 5 | strength = triples(strength); 6 | println!("My strength is now {}", strength); // 78 7 | 8 | // function taking another function as parameter: 9 | strength = again(triples, strength); 10 | println!("I got so lucky to turn my strength into {}", strength); // 702 (= 3 * 3 * 78) 11 | 12 | // closures instead of a named function: 13 | strength = 78; 14 | let triples = |n| { 3 * n }; // a closure 15 | // closures infer the types of their arguments and return value types 16 | strength = again(triples, strength); 17 | println!("My strength is now {}", strength); // 702 18 | 19 | // inlining: 20 | strength = 78; 21 | strength = again(|n| {3 * n} , strength); // an inline closure 22 | // simplified without { }: 23 | // strength = again(|n| 3 * n , strength); // an inline closure 24 | println!("My strength is now {}", strength); // 702 25 | 26 | // a closure has access to (captures) the variables in its scope: 27 | let x: i32 = 42; 28 | let print_add = |s| { 29 | println!("x is {}", x); 30 | x + s 31 | }; 32 | // || {...} is a closure which takes no arguments 33 | // each closure has its own unique type 34 | let res = print_add(strength); // <- here the closure is called "x is 42" 35 | assert_eq!(res, 744); // 42 + 702 36 | 37 | // a moving closure: 38 | let mut m: i32 = 42; 39 | let print_add_move = move |s| { 40 | println!("m is {}", m); 41 | m + s 42 | }; 43 | let res = print_add_move(strength); 44 | println!("m is {}", m); 45 | m = 52; 46 | println!("m is {}", m); 47 | assert_eq!(res, 744); // 42 + 702 48 | } 49 | 50 | fn triples(s: i32) -> i32 { 51 | 3 * s 52 | } 53 | 54 | // this function does exactly the same as function triples: 55 | fn triplesref(s: &i32) -> i32 { 56 | 3 * *s 57 | } 58 | 59 | fn again i32>(f: F, s: i32) -> i32 { 60 | f(f(s)) 61 | } 62 | // Output: 63 | // My tripled strength equals 78 64 | // My strength is still 26 65 | // My strength is now 78 66 | // I got so lucky to turn my strength into 702 67 | // My strength is now 702 68 | // My strength is now 702 69 | // x is 42 70 | // m is 42 71 | // m is 42 72 | // m is 52 73 | -------------------------------------------------------------------------------- /Chapter05/code/input_number.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn main() { 4 | println!("Give an integer number bigger than 0:"); 5 | let mut buf = String::new(); 6 | io::stdin().read_line(&mut buf) 7 | .ok() 8 | .expect("Failed to read line"); 9 | let input_num: Result = buf.trim().parse(); 10 | let res = match input_num { 11 | Ok(num) => num, 12 | Err(_) => 0 13 | }; 14 | if res != 0 { 15 | println!("{}, that's a beautiful number", res); 16 | } 17 | else { 18 | println!("The input was not correct: {:?} ", input_num); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter05/code/input_number2.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn main() { 4 | println!("Give an integer number bigger than 0:"); 5 | let num = read_u32(); 6 | match num { 7 | Some(val) => println!("That's the number: {}", val), 8 | None => println!("Failed to read number.") 9 | } 10 | } 11 | 12 | fn read_u32() -> Option { 13 | let mut buf = String::new(); 14 | if io::stdin().read_line(&mut buf).is_ok() { 15 | let result = buf.trim().parse::(); 16 | return match result { 17 | Ok(value) => Some(value), 18 | Err(_) => None //Failed to parse 19 | }; 20 | } 21 | None //Failed to read from stream 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Chapter05/code/iterators.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // iterating over a range: 3 | let mut rng = 0..7; 4 | 5 | println!("> {:?}", rng.next()); // Some(0) 6 | println!("> {:?}", rng.next()); // Some(1) 7 | 8 | for n in rng { 9 | print!("{} - ", n); 10 | } // 2 - 3 - 4 - 5 - 6 - 11 | println!(""); 12 | 13 | // iterating over arrays and vectors: 14 | let aliens = ["Cherfer", "Fynock", "Shirack", "Zuxu"]; 15 | println!("Here are the aliens: "); 16 | for alien in aliens.iter() { 17 | print!("{} / ", alien) 18 | } 19 | // shorter way: 20 | println!("Here are the aliens again: "); 21 | for alien in &aliens { 22 | print!("{} / ", alien) 23 | } 24 | println!(""); 25 | 26 | println!("Here are the aliens in reverse: "); 27 | for alien in aliens.iter().rev() { 28 | print!("{} / ", alien) 29 | } 30 | 31 | // lazy iterator: 32 | let rng = 0..1000_000; 33 | } 34 | // > Some(0) 35 | // > Some(1) 36 | // 23456 37 | // 2 - 3 - 4 - 5 - 6 - 38 | // Here are the aliens: 39 | // Cherfer / Fynock / Shirack / Zuxu / 40 | // Here are the aliens again: 41 | // Cherfer / Fynock / Shirack / Zuxu / 42 | // Here are the aliens in reverse: 43 | // Zuxu / Shirack / Fynock / Cherfer / -------------------------------------------------------------------------------- /Chapter05/code/sqrt_match.rs: -------------------------------------------------------------------------------- 1 | use std::f32; 2 | 3 | fn main() { 4 | // using Result 5 | let m = sqroot(42.0); 6 | // let m = sqroot(-5.0); 7 | 8 | // match m { 9 | // Ok(sq) => println!("The square root of 42 is {}", sq), 10 | // Err(str) => println!("{}", str) 11 | // } 12 | 13 | let res = match m { 14 | Ok(sq) => sq, 15 | Err(_) => -1.0 16 | }; 17 | println!("res is {}", res); 18 | } 19 | 20 | fn sqroot(r: f32) -> Result { 21 | if r < 0.0 { 22 | return Err("Number cannot be negative!".to_string()); 23 | } 24 | // assert!(r >= 0.0, "Number cannot be negative!"); 25 | Ok(f32::sqrt(r)) 26 | } 27 | // The square root of 42 is 6.480741 28 | // mres is 6.480741 29 | // for m == -5.0: Number cannot be negative! 30 | // res is 6.4807405 -------------------------------------------------------------------------------- /Chapter05/code/try_input_number.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::error; 3 | 4 | fn main() { 5 | println!("Give a positive secret number: "); 6 | match input_num() { 7 | Ok(v) => println!("Input value is: {}", v), 8 | Err(e) => println!("Error - Please input an integer number!: {}", e) 9 | } 10 | } 11 | 12 | // try! macro 13 | // fn input_num() -> Result> { 14 | // let mut input = String::new(); 15 | // try!(io::stdin().read_line(&mut input)); 16 | // Ok(try!(input.trim().parse())) 17 | // } 18 | 19 | // error propagation operator ? 20 | fn input_num() -> Result> { 21 | let mut input = String::new(); 22 | io::stdin().read_line(&mut input)?; 23 | Ok(input.trim().parse()?) 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Chapter05/exercises/complex.rs: -------------------------------------------------------------------------------- 1 | use std::f64; 2 | 3 | struct Complex { 4 | real: f64, 5 | imag: f64 6 | } 7 | 8 | impl Complex { 9 | fn new(re: f64, im: f64) -> Complex { 10 | Complex{ real: re, imag: im } 11 | } 12 | 13 | fn to_string(&self) -> String { 14 | if self.imag > 0.0 { format!("{} + {}i", self.real, self.imag) } 15 | else if self.imag < 0.0 { format!("{} - {}i", self.real, f64::abs(self.imag)) } 16 | else { format!("{}", self.real) } 17 | } 18 | 19 | fn add(&self, c: Complex) -> Complex { 20 | Complex{ real: self.real + c.real, imag: self.imag + c.imag } 21 | } 22 | 23 | fn times_ten(&mut self) { 24 | self.real = 10.0 * self.real; 25 | self.imag = 10.0 * self.imag; 26 | } 27 | 28 | fn abs(&self) -> f64 { 29 | f64::sqrt((self.real * self.real) + (self.imag * self.imag)) 30 | } 31 | 32 | } 33 | 34 | fn main() { 35 | let c1 = Complex{ real: 2.0, imag: 5.0 }; 36 | // same number, but with constructor new: 37 | let mut c2 = Complex::new(2.0, 5.0); 38 | // println!("{:?}", c1); 39 | println!("{}", c2.to_string()); // 2 + 5i 40 | let c3 = Complex::new(2.0, -5.0); 41 | println!("{}", c3.to_string()); // 2 - 5i 42 | let c4 = Complex::new(1.2, 4.2); 43 | println!("{}", c2.add(c4).to_string()); // 3.2 + 9.2i 44 | println!("{}", c2.add(c3).to_string()); // 4 45 | // println!("{}", c2.times_ten().to_string()); // 20 + 50i 46 | c2.times_ten(); 47 | println!("{}", c2.to_string()); // 20 + 50i 48 | println!("{}", c1.abs()); // 5.385165 49 | } -------------------------------------------------------------------------------- /Chapter05/exercises/draw_trait.rs: -------------------------------------------------------------------------------- 1 | trait Draw { 2 | fn draw(&self); 3 | } 4 | 5 | struct S1 { 6 | data_s1: i32 7 | } 8 | 9 | struct S2 { 10 | data_s2: f64 11 | } 12 | 13 | impl Draw for S1 { 14 | fn draw(&self) { 15 | println!("{}", self.data_s1); 16 | } 17 | } 18 | 19 | impl Draw for S2 { 20 | fn draw(&self) { 21 | println!("{}", self.data_s2); 22 | } 23 | } 24 | 25 | fn draw_object(object: T) { 26 | println!("Going to draw an object:"); 27 | object.draw(); 28 | println!("Look how beautiful!"); 29 | } 30 | 31 | 32 | fn main() { 33 | let s1 = S1 { data_s1: 42 }; 34 | let s2 = S2 { data_s2: 42.0 }; 35 | draw_object(s1); // OK, S1 implements Draw. 36 | draw_object(s2); // OK, S2 implements Draw. 37 | // draw_object(42.0); // error: the trait `Draw` is not implemented for the type `_` 38 | } 39 | // Going to draw an object: 40 | // 42 41 | // Look how beautiful! 42 | // Going to draw an object: 43 | // 42 44 | // Look how beautiful! -------------------------------------------------------------------------------- /Chapter05/exercises/fold.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let sum = (0..101).fold(0, |sum, n| sum + n); 3 | println!("{}", sum); // 5050 4 | 5 | let prcub = (1..6).fold(1, |prcub, n| prcub * (n * n * n)); 6 | println!("{}", prcub); // 1728000 7 | 8 | let arr = [1, 9, 2, 3, 14, 12]; 9 | let res = arr.iter().fold(0, |acc, item| acc - item); 10 | println!("{}", res) // -41 11 | } -------------------------------------------------------------------------------- /Chapter05/exercises/range_next.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut rng = 0..7; 3 | 4 | loop { 5 | match rng.next() { 6 | Some(val) => print!("{} - ", val), 7 | None => break 8 | } 9 | } 10 | } 11 | // 0 - 1 - 2 - 3 - 4 - 5 - 6 - -------------------------------------------------------------------------------- /Chapter06/code/builder_pattern.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | name: &'static str, 3 | health: u32, 4 | damage: u32 5 | } 6 | 7 | struct AlienBuilder { 8 | name: &'static str, 9 | health: u32, 10 | damage: u32 11 | } 12 | 13 | impl AlienBuilder { 14 | fn new() -> Self { 15 | AlienBuilder { name: "Walker", health: 100, damage: 10 } 16 | } 17 | 18 | fn name(&mut self, n: &'static str) -> &mut AlienBuilder { 19 | self.name = n; 20 | self 21 | } 22 | 23 | fn health(&mut self, h: u32) -> &mut AlienBuilder { 24 | self.health = h; 25 | self 26 | } 27 | 28 | fn damage(&mut self, d: u32) -> &mut AlienBuilder { 29 | self.damage = d; 30 | self 31 | } 32 | 33 | fn finish(&self) -> Alien { 34 | Alien { name: self.name, health: self.health, damage: self.damage } 35 | } 36 | } 37 | 38 | fn main() { 39 | let al1 = AlienBuilder::new() 40 | .name("Bork") 41 | .health(80) 42 | .damage(20) 43 | .finish(); 44 | println!("name: {}", al1.name); 45 | println!("health: {}", al1.health); 46 | } 47 | // name: Bork 48 | // health: 80 -------------------------------------------------------------------------------- /Chapter06/code/constructor_pattern.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | name: &'static str, 3 | health: u32, 4 | damage: u32 5 | } 6 | 7 | impl Alien { 8 | fn new(s: &'static str, mut h: u32, d: u32) -> Self { 9 | if h > 100 { h = 100; } 10 | Alien { name: s, health: h, damage: d } 11 | } 12 | 13 | pub fn default() -> Self { 14 | Alien::new("Walker", 100, 10) 15 | } 16 | 17 | pub fn give_health(h: u32) -> Self { 18 | Alien::new("Zombie", h, 5) 19 | } 20 | } 21 | 22 | fn main() { 23 | let al1 = Alien{ name: "Bork", health: 100, damage: 5 }; 24 | let al2 = Alien::new("Berserk", 150, 15); 25 | println!("Alien 1 is a {} and inflicts {} damage points", al1.name, al1.damage); 26 | let al3 = Alien::default(); 27 | println!("Alien 3 is a {} and inflicts {} damage points", al3.name, al3.damage); 28 | let al4 = Alien::give_health(75); 29 | println!("Alien 4 is a {} and inflicts {} damage points", al4.name, al4.damage); 30 | } 31 | // Alien 1 is a Bork and inflicts 5 damage points 32 | // Alien 3 is a Walker and inflicts 10 damage points 33 | // Alien 4 is a Zombie and inflicts 5 damage points 34 | 35 | -------------------------------------------------------------------------------- /Chapter06/code/dispatch.rs: -------------------------------------------------------------------------------- 1 | struct Circle; 2 | struct Triangle; 3 | 4 | trait Figure { 5 | fn print(&self); 6 | } 7 | 8 | impl Figure for Circle { 9 | fn print(&self) { 10 | println!("Circle"); 11 | } 12 | } 13 | 14 | impl Figure for Triangle { 15 | fn print(&self) { 16 | println!("Triangle"); 17 | } 18 | } 19 | 20 | // static dispatch with trait bounds: 21 | fn log(figure: &T) { 22 | figure.print(); 23 | } 24 | 25 | // dynamic dispatch: function takes a trait object 26 | fn logd(figure: &Figure) { 27 | figure.print(); 28 | } 29 | 30 | fn main() { 31 | // static dispatch 32 | let circle = Circle; 33 | let triangle = Triangle; 34 | 35 | log(&circle); 36 | log(&triangle); 37 | 38 | // dynamic dispatch: 39 | let mut figures: Vec> = Vec::new(); 40 | figures.push(Box::new(Circle)); 41 | figures.push(Box::new(Triangle)); 42 | 43 | // the precise type of figure can only be known at runtime: 44 | for figure in figures { 45 | // log(&*figure); // error: the trait `core::marker::Sized` is not implemented for the type `Figure` 46 | logd(&*figure); 47 | } 48 | } 49 | // Circle 50 | // Triangle 51 | // Circle 52 | // Triangle -------------------------------------------------------------------------------- /Chapter06/code/impl_add.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Add; 2 | 3 | #[derive(Debug)] 4 | struct AType { 5 | value: i32, 6 | } 7 | 8 | impl AType { 9 | fn new(value: i32) -> AType { 10 | AType { value: value } 11 | } 12 | } 13 | 14 | impl Add for AType { 15 | type Output = AType; 16 | 17 | fn add(self, other: AType) -> AType { 18 | AType { value: self.value + other.value } 19 | } 20 | } 21 | 22 | 23 | fn main() { 24 | let at1 = AType{ value: 7 }; 25 | let at2 = AType{ value: 42 }; 26 | let at3 = at1.add(at2); 27 | println!("{:?}", at3); 28 | let at4 = AType{ value: 2 }; 29 | let at5 = AType{ value: 108 }; 30 | let at6 = at4 + at5; 31 | println!("{:?}", at6); 32 | } 33 | // AType { value: 49 } 34 | // AType { value: 110 } 35 | -------------------------------------------------------------------------------- /Chapter06/code/method_enum.rs: -------------------------------------------------------------------------------- 1 | enum Day { 2 | Monday, 3 | Tuesday, 4 | Wednesday, 5 | Thursday, 6 | Friday, 7 | Saturday, 8 | Sunday, 9 | } 10 | 11 | impl Day { 12 | fn mood(&self) { 13 | println!("{}", match *self { 14 | Day::Friday => "it's friday!", 15 | Day::Saturday | Day::Sunday => "weekend :-)", 16 | _ => "weekday...", 17 | }) 18 | } 19 | } 20 | 21 | fn main() { 22 | let today = Day::Tuesday; 23 | today.mood(); 24 | } 25 | // weekday... 26 | -------------------------------------------------------------------------------- /Chapter06/code/methods.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | health: u32, 3 | damage: u32 4 | } 5 | 6 | impl Alien { 7 | fn new(mut h: u32, d: u32) -> Alien { 8 | // constraints: 9 | if h > 100 { h = 100; } 10 | Alien { health: h, damage: d } 11 | } 12 | 13 | fn warn() -> &'static str { 14 | "Leave this planet immediately or perish!" 15 | } 16 | 17 | fn attack(&self) { 18 | println!("I attack! Your health lowers with {} damage points.", self.damage); 19 | } 20 | 21 | // multiple errors: 22 | // cannot assign to immutable field self.health 23 | // solution: &mut self 24 | // duplicate definition of value `attack` 25 | // solution: give method a different name 26 | // fn attack(&mut self) { 27 | // self.health -= 10; 28 | // } 29 | 30 | fn attack_and_suffer(&mut self, damage_from_other: u32) { 31 | println!("I attack! Your health lowers with {} damage points.", self.damage); 32 | self.health -= damage_from_other; 33 | } 34 | } 35 | 36 | fn main() { 37 | let mut bork = Alien{ health: 100, damage: 5 }; 38 | let mut berserk = Alien::new(150, 15); 39 | println!("The berserk's health at birth is: {}", berserk.health); 40 | println!("{}", Alien::warn()); 41 | berserk.attack(); 42 | println!("The berserk's health is: {}", berserk.health); 43 | berserk.attack_and_suffer(31); 44 | println!("After attack the berserk's health is: {}", berserk.health); 45 | } 46 | // The berserk's health at birth is: 100 47 | // Leave this planet immediately or perish! 48 | // I attack! Your health lowers with 15 damage points. 49 | // The berserk's health is: 100 50 | // After attack the berserk's health is: 69 -------------------------------------------------------------------------------- /Chapter06/code/paradigm.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let str1 = "abc"; 3 | println!("{}", str1.len()); // 3 4 | println!("{}", str::len(str1)); // 3 5 | } -------------------------------------------------------------------------------- /Chapter06/code/super_traits.rs: -------------------------------------------------------------------------------- 1 | struct Zombie { health: u32, damage: u32 } 2 | 3 | trait SuperMonster { 4 | fn super1(&self); 5 | } 6 | 7 | trait Monster : SuperMonster { 8 | fn new(hlt: u32, dam: u32) -> Self; 9 | fn attack(&self); 10 | fn noise(&self) -> &'static str; 11 | } 12 | 13 | impl SuperMonster for Zombie { 14 | fn super1(&self) { 15 | println!("I am a SuperMonster"); 16 | } 17 | } 18 | 19 | impl Monster for Zombie { 20 | fn new(mut h: u32, d: u32) -> Zombie { 21 | if h > 100 { h = 100; } 22 | Zombie { health: h, damage: d } 23 | } 24 | 25 | fn attack(&self) { 26 | println!("The Zombie bites! Your health lowers with {} damage points.", 2 * self.damage); 27 | } 28 | 29 | fn noise(&self) -> &'static str { 30 | "Aaargh!" 31 | } 32 | } 33 | 34 | fn main() { 35 | let zmb1 = Zombie { health: 75, damage: 15 }; 36 | println!("Oh no, I hear: {}", zmb1.noise()); 37 | zmb1.super1(); 38 | } 39 | // Oh no, I hear: Aaargh! 40 | // I am a SuperMonster -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trait_constraints" 3 | version = "0.0.1" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [[bin]] 7 | name = "trait_constraints" 8 | 9 | [dependencies] 10 | num = "*" -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/src/trait_constraints.rs: -------------------------------------------------------------------------------- 1 | extern crate num; 2 | use num::traits::Float; 3 | 4 | fn main() { 5 | println!("The square root of {} is {:?}", 42.0f32, sqroot(42.0f32) ); 6 | println!("The square root of {} is {:?}", 42.0f64, sqroot(42.0f64) ); 7 | // println!("The square root of {} is {:?}", 42, sqroot(42)); 8 | } 9 | 10 | // errors: binary operation `<` cannot be applied to type `T` 11 | // no function or associated item named `sqrt` found for type `T` in 12 | // the current scope 13 | // fn sqroot(r: T) -> Result { 14 | // if r < 0.0 { 15 | // return Err("Number cannot be negative!".to_string()); 16 | // } 17 | // Ok(T::sqrt(r)) 18 | // } 19 | 20 | fn sqroot(r: T) -> Result { 21 | if r < num::zero() { 22 | return Err("Number cannot be negative!".to_string()); 23 | } 24 | Ok(num::traits::Float::sqrt(r)) 25 | } 26 | 27 | // trait constraint written with where clause syntax: 28 | fn sqroot2(r: T) -> Result where T: num::traits::Float { 29 | if r < num::zero() { 30 | return Err("Number cannot be negative!".to_string()); 31 | } 32 | Ok(num::traits::Float::sqrt(r)) 33 | } 34 | // The square root of 42 is Ok(6.4807405) 35 | // The square root of 42 is Ok(6.48074069840786) 36 | 37 | // fn multc(x: T, y: U) {} 38 | // fn multc(x: T, y: U) where T: Trait1, U: Trait1 + Trait2 {} 39 | 40 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.cargo-lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/.cargo-lock -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-2903dbbf6aef2ddf/dep-lib-libc-2903dbbf6aef2ddf: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libc-2903dbbf6aef2ddf.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libc-2903dbbf6aef2ddf.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs: 10 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs: 11 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-2903dbbf6aef2ddf/lib-libc-2903dbbf6aef2ddf: -------------------------------------------------------------------------------- 1 | 0e5c5d2fa69565e6 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-2903dbbf6aef2ddf/lib-libc-2903dbbf6aef2ddf.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"use_std\"]","target":7775660019970155459,"profile":14119667493710126711,"deps":[],"local":{"Precalculated":"0.2.28"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-51e019ba1c48043b/dep-lib-libc-51e019ba1c48043b: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\liblibc-51e019ba1c48043b.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libc-51e019ba1c48043b.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\macros.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\dox.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\windows.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\redox.rs: 10 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\libc-0.2.28\src\unix\mod.rs: 11 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-51e019ba1c48043b/lib-libc-51e019ba1c48043b: -------------------------------------------------------------------------------- 1 | 792091084af03b1c -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/libc-51e019ba1c48043b/lib-libc-51e019ba1c48043b.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"use_std\"]","target":7775660019970155459,"profile":731176819336294830,"deps":[],"local":{"Precalculated":"0.2.28"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-5589f3536e774f5d/dep-lib-num-5589f3536e774f5d: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum-5589f3536e774f5d.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num-5589f3536e774f5d.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-5589f3536e774f5d/lib-num-5589f3536e774f5d: -------------------------------------------------------------------------------- 1 | dd83304bf60b2364 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-5589f3536e774f5d/lib-num-5589f3536e774f5d.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"bigint\", \"complex\", \"default\", \"num-bigint\", \"num-complex\", \"num-rational\", \"rational\", \"rustc-serialize\"]","target":17582385105422339245,"profile":731176819336294830,"deps":[["num-bigint v0.1.40",10001087861839492792],["num-complex v0.1.40",8531435992111289326],["num-integer v0.1.35",1975706337897333649],["num-iter v0.1.34",6905484248138481712],["num-rational v0.1.39",5755834924593099472],["num-traits v0.1.40",13893615653117815278]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-0600fe7406f6efc3/dep-lib-num_bigint-0600fe7406f6efc3: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum_bigint-0600fe7406f6efc3.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_bigint-0600fe7406f6efc3.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs: 10 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-0600fe7406f6efc3/lib-num_bigint-0600fe7406f6efc3: -------------------------------------------------------------------------------- 1 | b8f6691c6c00cb8a -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-0600fe7406f6efc3/lib-num_bigint-0600fe7406f6efc3.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"rand\", \"rustc-serialize\"]","target":6362754662412431275,"profile":731176819336294830,"deps":[["num-integer v0.1.35",1975706337897333649],["num-traits v0.1.40",13893615653117815278],["rand v0.3.15",3866154059313530386],["rustc-serialize v0.3.24",16128146368769509119]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-549b3dc61a1ab09c/dep-lib-num_bigint-549b3dc61a1ab09c: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_bigint-549b3dc61a1ab09c.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_bigint-549b3dc61a1ab09c.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\macros.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\biguint.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\algorithms.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-bigint-0.1.40\src\bigint.rs: 10 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-549b3dc61a1ab09c/lib-num_bigint-549b3dc61a1ab09c: -------------------------------------------------------------------------------- 1 | bed346bf4dbf59ad -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-bigint-549b3dc61a1ab09c/lib-num_bigint-549b3dc61a1ab09c.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"rand\", \"rustc-serialize\"]","target":6362754662412431275,"profile":14119667493710126711,"deps":[["num-integer v0.1.35",5910302312933320057],["num-traits v0.1.40",16633007538405627126],["rand v0.3.15",4168803037842253701],["rustc-serialize v0.3.24",13597090111879495535]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-c6ee85dc30c1af34/dep-lib-num_complex-c6ee85dc30c1af34: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum_complex-c6ee85dc30c1af34.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_complex-c6ee85dc30c1af34.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-c6ee85dc30c1af34/lib-num_complex-c6ee85dc30c1af34: -------------------------------------------------------------------------------- 1 | ee93c655d5bf6576 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-c6ee85dc30c1af34/lib-num_complex-c6ee85dc30c1af34.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"rustc-serialize\"]","target":10996964265869989617,"profile":731176819336294830,"deps":[["num-traits v0.1.40",13893615653117815278],["rustc-serialize v0.3.24",16128146368769509119]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-edf2967894911149/dep-lib-num_complex-edf2967894911149: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_complex-edf2967894911149.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_complex-edf2967894911149.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-complex-0.1.40\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-edf2967894911149/lib-num_complex-edf2967894911149: -------------------------------------------------------------------------------- 1 | 1b6fe4b704947c85 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-complex-edf2967894911149/lib-num_complex-edf2967894911149.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"default\", \"rustc-serialize\"]","target":10996964265869989617,"profile":14119667493710126711,"deps":[["num-traits v0.1.40",16633007538405627126],["rustc-serialize v0.3.24",13597090111879495535]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-ded7f16ba22e8735/dep-lib-num-ded7f16ba22e8735: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num-ded7f16ba22e8735.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num-ded7f16ba22e8735.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-0.1.40\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-ded7f16ba22e8735/lib-num-ded7f16ba22e8735: -------------------------------------------------------------------------------- 1 | 3432d73b15ec8463 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-ded7f16ba22e8735/lib-num-ded7f16ba22e8735.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"bigint\", \"complex\", \"default\", \"num-bigint\", \"num-complex\", \"num-rational\", \"rational\", \"rustc-serialize\"]","target":17582385105422339245,"profile":14119667493710126711,"deps":[["num-bigint v0.1.40",12491225382131258302],["num-complex v0.1.40",9618725652142518043],["num-integer v0.1.35",5910302312933320057],["num-iter v0.1.34",17334763473969455506],["num-rational v0.1.39",13101264412823886783],["num-traits v0.1.40",16633007538405627126]],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-133aa4776c28e844/dep-lib-num_integer-133aa4776c28e844: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum_integer-133aa4776c28e844.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_integer-133aa4776c28e844.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-133aa4776c28e844/lib-num_integer-133aa4776c28e844: -------------------------------------------------------------------------------- 1 | 91c3db52721e6b1b -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-133aa4776c28e844/lib-num_integer-133aa4776c28e844.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":2499047663451976504,"profile":731176819336294830,"deps":[["num-traits v0.1.40",13893615653117815278]],"local":{"Precalculated":"0.1.35"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-27c2de924efa446c/dep-lib-num_integer-27c2de924efa446c: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_integer-27c2de924efa446c.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_integer-27c2de924efa446c.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-integer-0.1.35\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-27c2de924efa446c/lib-num_integer-27c2de924efa446c: -------------------------------------------------------------------------------- 1 | 79658fb5a39c0552 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-integer-27c2de924efa446c/lib-num_integer-27c2de924efa446c.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":2499047663451976504,"profile":14119667493710126711,"deps":[["num-traits v0.1.40",16633007538405627126]],"local":{"Precalculated":"0.1.35"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-89e152564970c817/dep-lib-num_iter-89e152564970c817: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum_iter-89e152564970c817.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_iter-89e152564970c817.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-89e152564970c817/lib-num_iter-89e152564970c817: -------------------------------------------------------------------------------- 1 | 3080593c5635d55f -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-89e152564970c817/lib-num_iter-89e152564970c817.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":9783223229852757968,"profile":731176819336294830,"deps":[["num-integer v0.1.35",1975706337897333649],["num-traits v0.1.40",13893615653117815278]],"local":{"Precalculated":"0.1.34"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-ecbfdf4df71f0e1c/dep-lib-num_iter-ecbfdf4df71f0e1c: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_iter-ecbfdf4df71f0e1c.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_iter-ecbfdf4df71f0e1c.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-iter-0.1.34\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-ecbfdf4df71f0e1c/lib-num_iter-ecbfdf4df71f0e1c: -------------------------------------------------------------------------------- 1 | 92a15d3b897391f0 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-iter-ecbfdf4df71f0e1c/lib-num_iter-ecbfdf4df71f0e1c.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":9783223229852757968,"profile":14119667493710126711,"deps":[["num-integer v0.1.35",5910302312933320057],["num-traits v0.1.40",16633007538405627126]],"local":{"Precalculated":"0.1.34"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-01cc31e8816a22bc/dep-lib-num_rational-01cc31e8816a22bc: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_rational-01cc31e8816a22bc.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_rational-01cc31e8816a22bc.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-01cc31e8816a22bc/lib-num_rational-01cc31e8816a22bc: -------------------------------------------------------------------------------- 1 | bf9bd5ea910ad1b5 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-01cc31e8816a22bc/lib-num_rational-01cc31e8816a22bc.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"bigint\", \"default\", \"num-bigint\", \"rustc-serialize\"]","target":14203037239526870534,"profile":14119667493710126711,"deps":[["num-bigint v0.1.40",12491225382131258302],["num-integer v0.1.35",5910302312933320057],["num-traits v0.1.40",16633007538405627126],["rustc-serialize v0.3.24",13597090111879495535]],"local":{"Precalculated":"0.1.39"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-3cf12afed100f639/dep-lib-num_rational-3cf12afed100f639: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\libnum_rational-3cf12afed100f639.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\num_rational-3cf12afed100f639.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\num-rational-0.1.39\src\lib.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-3cf12afed100f639/lib-num_rational-3cf12afed100f639: -------------------------------------------------------------------------------- 1 | d0b228425ed5e04f -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-rational-3cf12afed100f639/lib-num_rational-3cf12afed100f639.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[\"bigint\", \"default\", \"num-bigint\", \"rustc-serialize\"]","target":14203037239526870534,"profile":731176819336294830,"deps":[["num-bigint v0.1.40",10001087861839492792],["num-integer v0.1.35",1975706337897333649],["num-traits v0.1.40",13893615653117815278],["rustc-serialize v0.3.24",16128146368769509119]],"local":{"Precalculated":"0.1.39"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-traits-1297a437aebb5e06/lib-num_traits-1297a437aebb5e06: -------------------------------------------------------------------------------- 1 | f6d40f113b50d4e6 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-traits-1297a437aebb5e06/lib-num_traits-1297a437aebb5e06.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":841675786306361799,"profile":14119667493710126711,"deps":[],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-traits-2ab8385458bc0c23/lib-num_traits-2ab8385458bc0c23: -------------------------------------------------------------------------------- 1 | eee9e431d309d0c0 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/num-traits-2ab8385458bc0c23/lib-num_traits-2ab8385458bc0c23.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":841675786306361799,"profile":731176819336294830,"deps":[],"local":{"Precalculated":"0.1.40"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rand-92319875a3b5e926/lib-rand-92319875a3b5e926: -------------------------------------------------------------------------------- 1 | 12465118a256a735 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rand-92319875a3b5e926/lib-rand-92319875a3b5e926.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":7654643613446124965,"profile":731176819336294830,"deps":[["libc v0.2.28",2034483857449885817]],"local":{"Precalculated":"0.3.15"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rand-ef4d4ec4f3682cc9/lib-rand-ef4d4ec4f3682cc9: -------------------------------------------------------------------------------- 1 | 852728914690da39 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rand-ef4d4ec4f3682cc9/lib-rand-ef4d4ec4f3682cc9.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":7654643613446124965,"profile":14119667493710126711,"deps":[["libc v0.2.28",16601840142362958862]],"local":{"Precalculated":"0.3.15"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-07daa0fc98cd1a5d/dep-lib-rustc_serialize-07daa0fc98cd1a5d: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\librustc_serialize-07daa0fc98cd1a5d.rlib: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\rustc_serialize-07daa0fc98cd1a5d.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs: 10 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs: 11 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-07daa0fc98cd1a5d/lib-rustc_serialize-07daa0fc98cd1a5d: -------------------------------------------------------------------------------- 1 | ff4603fcabafd2df -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-07daa0fc98cd1a5d/lib-rustc_serialize-07daa0fc98cd1a5d.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":4000591347888664404,"profile":731176819336294830,"deps":[],"local":{"Precalculated":"0.3.24"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-6e8c8043064c4717/dep-lib-rustc_serialize-6e8c8043064c4717: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\rustc_serialize-6e8c8043064c4717.rmeta: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\rustc_serialize-6e8c8043064c4717.d: C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs 4 | 5 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\lib.rs: 6 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\serialize.rs: 7 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\collection_impls.rs: 8 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\base64.rs: 9 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\hex.rs: 10 | C:\Users\CVO\.cargo\registry\src\github.com-1ecc6299db9ec823\rustc-serialize-0.3.24\src\json.rs: 11 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-6e8c8043064c4717/lib-rustc_serialize-6e8c8043064c4717: -------------------------------------------------------------------------------- 1 | 6fbf8d916a91b2bc -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/rustc-serialize-6e8c8043064c4717/lib-rustc_serialize-6e8c8043064c4717.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":4000591347888664404,"profile":14119667493710126711,"deps":[],"local":{"Precalculated":"0.3.24"},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-639f937b259be757/bin-trait_constraints-639f937b259be757: -------------------------------------------------------------------------------- 1 | 4bae2b8e12c84cf9 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-639f937b259be757/bin-trait_constraints-639f937b259be757.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":9540591324539685138,"profile":14119667493710126711,"deps":[["num v0.1.40",7171116082623099444]],"local":{"MtimeBased":[[1500973142,29479700],"F:\\Rust\\2ndeditionRE\\Rust_Essentials\\Chapters\\Chapter 6 - Using traits and OOP in Rust\\code\\trait_constraints\\target\\debug\\.fingerprint\\trait_constraints-639f937b259be757\\dep-bin-trait_constraints-639f937b259be757"]},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-639f937b259be757/dep-bin-trait_constraints-639f937b259be757: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\trait_constraints-639f937b259be757.rmeta: src\trait_constraints.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\trait_constraints-639f937b259be757.d: src\trait_constraints.rs 4 | 5 | src\trait_constraints.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-82799a0b74ff0411/bin-trait_constraints-82799a0b74ff0411: -------------------------------------------------------------------------------- 1 | a98f2d71860e5863 -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-82799a0b74ff0411/bin-trait_constraints-82799a0b74ff0411.json: -------------------------------------------------------------------------------- 1 | {"rustc":4149359360477813300,"features":"[]","target":9540591324539685138,"profile":731176819336294830,"deps":[["num v0.1.40",7215624180428997597]],"local":{"MtimeBased":[[1500972808,46148600],"F:\\Rust\\2ndeditionRE\\Rust_Essentials\\Chapters\\Chapter 6 - Using traits and OOP in Rust\\code\\trait_constraints\\target\\debug\\.fingerprint\\trait_constraints-82799a0b74ff0411\\dep-bin-trait_constraints-82799a0b74ff0411"]},"rustflags":[]} -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/.fingerprint/trait_constraints-82799a0b74ff0411/dep-bin-trait_constraints-82799a0b74ff0411: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraintsF:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\trait_constraints-82799a0b74ff0411.exe: src\trait_constraints.rs 2 | 3 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter 6 - Using traits and OOP in Rust\code\trait_constraints\target\debug\deps\trait_constraints-82799a0b74ff0411.d: src\trait_constraints.rs 4 | 5 | src\trait_constraints.rs: 6 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/liblibc-2903dbbf6aef2ddf.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/liblibc-2903dbbf6aef2ddf.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/liblibc-51e019ba1c48043b.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/liblibc-51e019ba1c48043b.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum-5589f3536e774f5d.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum-5589f3536e774f5d.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum-ded7f16ba22e8735.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum-ded7f16ba22e8735.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_bigint-0600fe7406f6efc3.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_bigint-0600fe7406f6efc3.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_bigint-549b3dc61a1ab09c.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_bigint-549b3dc61a1ab09c.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_complex-c6ee85dc30c1af34.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_complex-c6ee85dc30c1af34.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_complex-edf2967894911149.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_complex-edf2967894911149.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_integer-133aa4776c28e844.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_integer-133aa4776c28e844.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_integer-27c2de924efa446c.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_integer-27c2de924efa446c.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_iter-89e152564970c817.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_iter-89e152564970c817.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_iter-ecbfdf4df71f0e1c.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_iter-ecbfdf4df71f0e1c.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_rational-01cc31e8816a22bc.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_rational-01cc31e8816a22bc.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_rational-3cf12afed100f639.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_rational-3cf12afed100f639.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_traits-1297a437aebb5e06.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_traits-1297a437aebb5e06.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/libnum_traits-2ab8385458bc0c23.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/libnum_traits-2ab8385458bc0c23.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/librand-92319875a3b5e926.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/librand-92319875a3b5e926.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/librand-ef4d4ec4f3682cc9.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/librand-ef4d4ec4f3682cc9.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/librustc_serialize-07daa0fc98cd1a5d.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/librustc_serialize-07daa0fc98cd1a5d.rlib -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/deps/librustc_serialize-6e8c8043064c4717.rmeta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter06/code/trait_constraints/target/debug/deps/librustc_serialize-6e8c8043064c4717.rmeta -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/libtrait_constraints.d: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter\ 6\ -\ Using\ traits\ and\ OOP\ in\ Rust\code\trait_constraints\target\debug\libtrait_constraints.rmeta: F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter\ 6\ -\ Using\ traits\ and\ OOP\ in\ Rust\code\trait_constraints\src\trait_constraints.rs 2 | -------------------------------------------------------------------------------- /Chapter06/code/trait_constraints/target/debug/trait_constraints.d: -------------------------------------------------------------------------------- 1 | F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter\ 6\ -\ Using\ traits\ and\ OOP\ in\ Rust\code\trait_constraints\target\debug\trait_constraints.exe: F:\Rust\2ndeditionRE\Rust_Essentials\Chapters\Chapter\ 6\ -\ Using\ traits\ and\ OOP\ in\ Rust\code\trait_constraints\src\trait_constraints.rs 2 | -------------------------------------------------------------------------------- /Chapter06/code/traits.rs: -------------------------------------------------------------------------------- 1 | struct Alien { health: u32, damage: u32 } 2 | 3 | #[derive(Debug)] 4 | struct Zombie { health: u32, damage: u32 } 5 | 6 | struct Predator { health: u32, damage: u32 } 7 | 8 | trait Monster { 9 | fn new(hlt: u32, dam: u32) -> Self; 10 | 11 | fn attack(&self); 12 | fn noise(&self) -> &'static str; 13 | 14 | fn attacks_with_sound(&self) { 15 | println!("The Monster attacks by making an awkward sound {}", self.noise()); 16 | } 17 | } 18 | 19 | impl Monster for Alien { 20 | fn new(mut h: u32, d: u32) -> Alien { 21 | // constraints: 22 | if h > 100 { h = 100; } 23 | Alien { health: h, damage: d } 24 | } 25 | 26 | fn attack(&self) { 27 | println!("I attack! Your health lowers with {} damage points.", self.damage); 28 | } 29 | 30 | fn noise(&self) -> &'static str { 31 | "Shriek!" 32 | } 33 | } 34 | 35 | impl Monster for Zombie { 36 | fn new(mut h: u32, d: u32) -> Zombie { 37 | // constraints: 38 | if h > 100 { h = 100; } 39 | Zombie { health: h, damage: d } 40 | } 41 | 42 | fn attack(&self) { 43 | println!("The Zombie bites! Your health lowers with {} damage points.", 2 * self.damage); 44 | } 45 | 46 | fn noise(&self) -> &'static str { 47 | "Aaargh!" 48 | } 49 | } 50 | 51 | // Predator still has to implement new and noise methods: 52 | // error[E0046]: not all trait items implemented, missing: `new`, `noise` 53 | // impl Monster for Predator { 54 | // fn attack(&self) { 55 | // println!("I bite you! Your health lowers with {} damage points.", 3 * self.damage); 56 | // } 57 | // } 58 | 59 | fn main() { 60 | let zmb1 = Zombie { health: 75, damage: 15 }; 61 | println!("Oh no, I hear: {}", zmb1.noise()); 62 | zmb1.attack(); 63 | println!("{:?}", zmb1); 64 | } 65 | // Oh no, I hear: Aaargh! 66 | // The Zombie bites! Your health lowers with 30 damage points. 67 | // Zombie { health: 75, damage: 15 } -------------------------------------------------------------------------------- /Chapter06/code/visitor_pattern.rs: -------------------------------------------------------------------------------- 1 | // structs: 2 | struct Point { 3 | x: f64, 4 | y: f64 5 | } 6 | 7 | struct Circle { 8 | center: Point, 9 | radius: f64, 10 | } 11 | 12 | struct Square { 13 | lowerLeftCorner: Point, 14 | side: f64, 15 | } 16 | 17 | // traits: 18 | trait ShapeVisitor { 19 | fn visit_circle(&mut self, c: &Circle); 20 | fn visit_square(&mut self, r: &Square); 21 | } 22 | 23 | trait Shape { 24 | fn accept(&self, sv: &mut V); 25 | } 26 | 27 | impl Shape for Circle { 28 | fn accept(&self, sv: &mut V) { 29 | sv.visit_circle(self); 30 | } 31 | } 32 | 33 | impl Shape for Square { 34 | fn accept(&self, sv: &mut V) { 35 | sv.visit_square(self); 36 | } 37 | } 38 | 39 | fn compute_area(s: &S) -> f64 { 40 | struct AreaCalculator { 41 | area: f64, 42 | } 43 | 44 | impl ShapeVisitor for AreaCalculator { 45 | fn visit_circle(&mut self, c: &Circle) { 46 | self.area = std::f64::consts::PI * c.radius * c.radius; 47 | } 48 | fn visit_square(&mut self, r: &Square) { 49 | self.area = r.side * r.side; 50 | } 51 | } 52 | 53 | let mut ac = AreaCalculator { area: 0.0 }; 54 | s.accept(&mut ac); 55 | ac.area 56 | } 57 | 58 | fn main() { 59 | let cn = Point{ x: 0.0, y: 0.0 }; 60 | let ci = Circle{ center: cn, radius: 1.0 }; 61 | let area = compute_area(&ci); 62 | println!("The area of the circle is {}", area); 63 | let cn = Point{ x: 0.0, y: 0.0 }; 64 | let sq = Square{ lowerLeftCorner: cn, side: 1.0 }; 65 | let area = compute_area(&sq); 66 | println!("The area of the square is {}", area); 67 | 68 | } 69 | // The area of the circle is 3.141592653589793 70 | // The area of the square is 1 -------------------------------------------------------------------------------- /Chapter06/code/write.rs: -------------------------------------------------------------------------------- 1 | use std::io::Write; // in order to be able to use write! on a vector 2 | 3 | fn main() { 4 | let mut vec1 = Vec::new(); 5 | write!(&mut vec1, "test"); 6 | println!("{:?}", vec1); 7 | } 8 | // [116, 101, 115, 116] 9 | -------------------------------------------------------------------------------- /Chapter06/exercises/complex.rs: -------------------------------------------------------------------------------- 1 | use std::f64; 2 | 3 | struct Complex { 4 | real: f64, 5 | imag: f64 6 | } 7 | 8 | impl Complex { 9 | fn new(re: f64, im: f64) -> Complex { 10 | Complex{ real: re, imag: im } 11 | } 12 | 13 | fn to_string(&self) -> String { 14 | if self.imag > 0.0 { format!("{} + {}i", self.real, self.imag) } 15 | else if self.imag < 0.0 { format!("{} - {}i", self.real, f64::abs(self.imag)) } 16 | else { format!("{}", self.real) } 17 | } 18 | 19 | fn add(&self, c: Complex) -> Complex { 20 | Complex{ real: self.real + c.real, imag: self.imag + c.imag } 21 | } 22 | 23 | fn times_ten(&mut self) { 24 | self.real = 10.0 * self.real; 25 | self.imag = 10.0 * self.imag; 26 | } 27 | 28 | fn abs(&self) -> f64 { 29 | f64::sqrt((self.real * self.real) + (self.imag * self.imag)) 30 | } 31 | 32 | } 33 | 34 | fn main() { 35 | let c1 = Complex{ real: 2.0, imag: 5.0 }; 36 | // same number, but with constructor new: 37 | let mut c2 = Complex::new(2.0, 5.0); 38 | // println!("{:?}", c1); 39 | println!("{}", c2.to_string()); // 2 + 5i 40 | let c3 = Complex::new(2.0, -5.0); 41 | println!("{}", c3.to_string()); // 2 - 5i 42 | let c4 = Complex::new(1.2, 4.2); 43 | println!("{}", c2.add(c4).to_string()); // 3.2 + 9.2i 44 | println!("{}", c2.add(c3).to_string()); // 4 45 | // println!("{}", c2.times_ten().to_string()); // 20 + 50i 46 | c2.times_ten(); 47 | println!("{}", c2.to_string()); // 20 + 50i 48 | println!("{}", c1.abs()); // 5.385164807134504 49 | } -------------------------------------------------------------------------------- /Chapter06/exercises/draw_trait.rs: -------------------------------------------------------------------------------- 1 | trait Draw { 2 | fn draw(&self); 3 | } 4 | 5 | struct S1 { 6 | data_s1: i32 7 | } 8 | 9 | struct S2 { 10 | data_s2: f64 11 | } 12 | 13 | impl Draw for S1 { 14 | fn draw(&self) { 15 | println!("***{}***", self.data_s1); 16 | } 17 | } 18 | 19 | impl Draw for S2 { 20 | fn draw(&self) { 21 | println!("***{}***", self.data_s2); 22 | } 23 | } 24 | 25 | fn draw_object(object: T) { 26 | println!("Going to draw an object:"); 27 | object.draw(); 28 | println!("Look how beautiful!"); 29 | } 30 | 31 | fn main() { 32 | let s1 = S1 { data_s1: 42 }; 33 | let s2 = S2 { data_s2: 42.0 }; 34 | draw_object(s1); // OK, S1 implements Draw. 35 | draw_object(s2); // OK, S2 implements Draw. 36 | // draw_object(42.0); // error[E0277]: the trait bound `{float}: Draw` is not satisfied 37 | } 38 | // Going to draw an object: 39 | // ***42*** 40 | // Look how beautiful! 41 | // Going to draw an object: 42 | // ***42*** 43 | // Look how beautiful! -------------------------------------------------------------------------------- /Chapter06/exercises/visitor_pattern_dd.rs: -------------------------------------------------------------------------------- 1 | // structs: 2 | struct Point { 3 | x: f64, 4 | y: f64 5 | } 6 | 7 | struct Circle { 8 | center: Point, 9 | radius: f64, 10 | } 11 | 12 | struct Square { 13 | lowerLeftCorner: Point, 14 | side: f64, 15 | } 16 | 17 | // traits: 18 | trait ShapeVisitor { 19 | fn visit_circle(&mut self, c: &Circle); 20 | fn visit_square(&mut self, r: &Square); 21 | } 22 | 23 | trait Shape { 24 | fn accept(&self, sv: &mut ShapeVisitor); 25 | } 26 | 27 | impl Shape for Circle { 28 | fn accept(&self, sv: &mut ShapeVisitor) { 29 | sv.visit_circle(self); 30 | } 31 | } 32 | 33 | impl Shape for Square { 34 | fn accept(&self, sv: &mut ShapeVisitor) { 35 | sv.visit_square(self); 36 | } 37 | } 38 | 39 | fn compute_area(s: &Shape) -> f64 { 40 | struct AreaCalculator { 41 | area: f64, 42 | } 43 | 44 | impl ShapeVisitor for AreaCalculator { 45 | fn visit_circle(&mut self, c: &Circle) { 46 | self.area = std::f64::consts::PI * c.radius * c.radius; 47 | } 48 | fn visit_square(&mut self, r: &Square) { 49 | self.area = r.side * r.side; 50 | } 51 | } 52 | 53 | let mut ac = AreaCalculator { area: 0.0 }; 54 | s.accept(&mut ac); 55 | ac.area 56 | } 57 | 58 | fn main() { 59 | let cn = Point{ x: 0.0, y: 0.0 }; 60 | let ci = Circle{ center: cn, radius: 1.0 }; 61 | let area = compute_area(&ci); 62 | println!("The area of the circle is {}", area); 63 | let cn = Point{ x: 0.0, y: 0.0 }; 64 | let sq = Square{ lowerLeftCorner: cn, side: 1.0 }; 65 | let area = compute_area(&sq); 66 | println!("The area of the square is {}", area); 67 | 68 | } 69 | // The area of the circle is 3.141592653589793 70 | // The area of the square is 1 -------------------------------------------------------------------------------- /Chapter07/code/boxes1.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | n_tentacles: u32, 4 | } 5 | 6 | fn main() { 7 | let mut a1 = Box::new(Alien{ planet: "Mars".to_string(), n_tentacles: 4 }); 8 | println!("{}", a1.n_tentacles); // 4 9 | 10 | let a2 = &mut a1; 11 | println!("{}", a2.planet ); // Mars 12 | a2.n_tentacles = 5; 13 | // error: cannot borrow `a1.n_tentacles` as immutable because `a1` is also borrowed as mutable 14 | // println!("{}", a1.n_tentacles); 15 | // error: cannot assign to `a1.planet` because it is borrowed 16 | // a1.planet = "Pluto".to_string(); 17 | 18 | // putting simple values on the heap: 19 | let n = Box::new(42); 20 | println!("{}", n); // 42 21 | // *n = 67; // error: cannot assign to immutable `Box` content `*n` 22 | let p = *n; 23 | println!("{}", p); // 42 24 | 25 | // p = 67; // error: re-assignment of immutable variable `p` 26 | // this is allowed: 27 | let mut p = *n; 28 | p = 67; 29 | println!("{}", p); // 67 30 | println!("n now still has value {}", n); // 42 31 | 32 | // another reference to n: 33 | let q = &*n; 34 | // let q = &42; 35 | println!("{}", q); // 42 36 | println!("{}", square(q)); // 1764 37 | } 38 | 39 | fn square(k: &i32) -> i32 { 40 | *k * *k 41 | } 42 | // 4 43 | // Mars 44 | // 42 45 | // 42 46 | // 67 47 | // n now still has value 42 48 | // 42 49 | // 1764 -------------------------------------------------------------------------------- /Chapter07/code/boxes2.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | n_tentacles: u32, 4 | } 5 | 6 | fn main() { 7 | // mutability can be changed by transfering ownership: 8 | let n = Box::new(42); 9 | let mut m = n; 10 | *m = 67; 11 | // println!("{}", n); // error: use of moved value: `n` 12 | println!("{}", m); // 67 13 | 14 | let mut a1 = Box::new(Alien{ planet: "Mars".to_string(), n_tentacles: 4 }); 15 | // a move occurs here because it is a Box type: 16 | let a2 = a1; 17 | println!("{}", a2.n_tentacles); // 4 18 | //println!("{}", a1.n_tentacles); // error: use of moved value: `a1.n_tentacles` 19 | // a2.n_tentacles = 5; // cannot assign to immutable field a2.n_tentacles 20 | use_alien(a2); 21 | // println!("{}", a2.n_tentacles); // error: use of moved value: `a2.n_tentacles` 22 | // use_alien2(&*a2); // use of moved value: `*a2` 23 | 24 | // automatic dereferencing: 25 | let ua = Box::new([1, 2, 3]); 26 | println!("{}", ua[0]); // 1 27 | 28 | } 29 | 30 | fn use_alien(a: Box) { 31 | println!("An alien from planet {} is freed", a.planet); 32 | } 33 | 34 | fn use_alien2(a: &Alien) { 35 | println!("An alien from planet {} is freed", a.planet); 36 | } 37 | 38 | struct Recurs { 39 | list: Vec, 40 | rec_list: Option> 41 | } 42 | 43 | // 67 44 | // 4 45 | // 4 46 | // An alien from planet Mars is freed 47 | // 1 -------------------------------------------------------------------------------- /Chapter07/code/boxes_experimental.rs: -------------------------------------------------------------------------------- 1 | // #![feature(box_patterns)] 2 | 3 | struct Alien { 4 | planet: String, 5 | n_tentacles: u32, 6 | } 7 | 8 | fn main() { 9 | // error: box expression syntax is experimental; you can call `Box::new` instead. 10 | // let a = box 5i32; 11 | // mutable reference to a boxed value: 12 | // let mut a0 = box Alien{ planet: "Mars".to_string(), no_tentacles: 4 }; 13 | // println!("{}", a0.no_tentacles); // 4 14 | 15 | // The value can be extracted by the de-structuring pattern: let box m = a; 16 | // a mechanism which is also called unboxing a into m. 17 | // extract the value: 18 | // let box m = a; 19 | // println!("{}", m); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter07/code/clone.rs: -------------------------------------------------------------------------------- 1 | struct Block { 2 | number: Box, 3 | } 4 | 5 | impl Clone for Block { 6 | fn clone(&self) -> Self { 7 | Block { number: self.number.clone() } 8 | } 9 | } 10 | 11 | fn print_block(block: Block) { 12 | println!("{:p}: {:?}", block.number, block.number); 13 | } 14 | 15 | fn main() { 16 | let block = Block { number: Box::new(1) }; 17 | println!("{:p}: {:?}", block.number, block.number); 18 | print_block(block.clone()); 19 | } 20 | // 0x20c5ca23b00: 1 21 | // 0x20c5ca2cbe0: 1 22 | -------------------------------------------------------------------------------- /Chapter07/code/drop.rs: -------------------------------------------------------------------------------- 1 | struct Block { 2 | number: i32 3 | } 4 | 5 | impl Drop for Block { 6 | fn drop(&mut self) { 7 | println!("Dropping!"); 8 | } 9 | } 10 | 11 | fn print_block(block: Block) { 12 | println!("In function print_block"); 13 | } 14 | 15 | fn main() { 16 | let block = Block{ number: 1 }; 17 | // move of value block: 18 | print_block(block); 19 | println!("Back in main!"); 20 | } 21 | // In function print_block 22 | // Dropping! 23 | // Back in main! -------------------------------------------------------------------------------- /Chapter07/code/lifetimes.rs: -------------------------------------------------------------------------------- 1 | struct Magician { 2 | name: &'static str, 3 | power: u32 4 | } 5 | 6 | // this code does not compile: 7 | // error: missing lifetime specifier [E0106] 8 | // struct MagicNumbers { 9 | // magn1: &u32, 10 | // magn2: &u32 11 | // } 12 | 13 | // this code is ok, both the struct and the fields have lifetime 'a: 14 | struct MagicNumbers<'a> { 15 | magn1: &'a u32, 16 | magn2: &'a u32 17 | } 18 | 19 | // #[derive(Debug)] 20 | // #[derive(Copy, Clone)] 21 | #[derive(Debug, Copy, Clone)] 22 | struct MagicNumber { 23 | value: u64 24 | } 25 | 26 | // impl Copy for MagicNumber {} 27 | // impl Clone for MagicNumber { 28 | // fn clone(&self) -> MagicNumber { 29 | // *self 30 | // } 31 | // } 32 | 33 | struct MagicNumber2 { 34 | value: u64 35 | } 36 | 37 | fn main() { 38 | // lifetimes restricted to a function: 39 | let n = 42u32; 40 | // copy behaviour: 41 | // no move, only a copy of the value from n to n2: 42 | let n2 = n; 43 | println!("The value of n2 is {}, the same as n", n2); 44 | 45 | let p = life(n); 46 | println!("p is: {}", p); // p is: 42 47 | // println!("{}", m); // error: unresolved name `m`. 48 | // println!("{}", o); // error: unresolved name `o`. 49 | 50 | // lifetime restricted to a code block: 51 | { 52 | let phi = 1.618; 53 | } 54 | // error: unresolved name `phi`. 55 | // println!("The value of phi is {}", phi); 56 | 57 | // let m = return_magician(); 58 | // println!("{} has {}", m.name, m.power); 59 | 60 | // copies because MagicNumber implements the Copy or Clone trait 61 | let mag = MagicNumber { value: 42 }; 62 | let mag2 = mag; 63 | let mag3 = mag; 64 | 65 | // mag, mag2 and mag3 are 3 different objects: their addresses are different: 66 | println!("address mag: {:p}", &mag); // address is 0x6ebbcff550 67 | println!("address mag2: {:p}", &mag2); // address is 0x6ebbcff558 68 | println!("address mag3: {:p}", &mag3); // address is 0x6ebbcff568 69 | 70 | let mag4 = mag.clone(); 71 | println!("address mag4: {:p}", &mag4); // address mag4: 0x7c0053f820 72 | 73 | // 74 | println!("mag is: {:?}", mag); 75 | } 76 | 77 | fn life(m: u32) -> u32 { 78 | let o = m; 79 | o 80 | } 81 | 82 | fn transform<'a>(s: &'a str) { /* ... */ } 83 | fn transform_without_lifetime(s: &str) { /* ... */ } 84 | 85 | // fn return_magician<'a>() -> &'a Magician { 86 | // let mag = Magician { name: "Gandalf", power: 4625 }; 87 | // &mag // error: `mag` does not live long enough 88 | // } 89 | 90 | // The value of n2 is 42, the same as n 91 | // p is: 42 92 | // address mag: 0x7c0053f708 93 | // address mag2: 0x7c0053f710 94 | // address mag3: 0x7c0053f720 95 | // address mag4: 0x7c0053f820 96 | // mag is: MagicNumber { value: 42 } -------------------------------------------------------------------------------- /Chapter07/code/linked_list.rs: -------------------------------------------------------------------------------- 1 | // Allow Cons and Nil to be referred to without namespacing 2 | use List::{Cons, Nil}; 3 | 4 | // A linked list node, which can take on any of these two variants 5 | enum List { 6 | // Cons: Tuple struct that wraps an element and a pointer to the next node 7 | Cons(u32, Box), 8 | // Nil: A node that signifies the end of the linked list 9 | Nil, 10 | } 11 | 12 | // generic List: 13 | enum GList { 14 | Cons(T, Box>), 15 | Nil, 16 | } 17 | 18 | // Methods can be attached to an enum 19 | impl List { 20 | // Create an empty list 21 | fn new() -> List { 22 | // `Nil` has type `List` 23 | Nil 24 | } 25 | 26 | // Consume a list, and return the same list with a new element at its front 27 | fn prepend(self, elem: u32) -> List { 28 | // `Cons` also has type List 29 | Cons(elem, Box::new(self)) 30 | } 31 | 32 | // Return the length of the list 33 | fn len(&self) -> u32 { 34 | // `self` has to be matched, because the behavior of this method 35 | // depends on the variant of `self` 36 | // `self` has type `&List`, and `*self` has type `List`, matching on a 37 | // concrete type `T` is preferred over a match on a reference `&T` 38 | match *self { 39 | // Can't take ownership of the tail, because `self` is borrowed; 40 | // instead take a reference to the tail 41 | Cons(_, ref tail) => 1 + tail.len(), 42 | // Base Case: An empty list has zero length 43 | Nil => 0 44 | } 45 | } 46 | 47 | // Return representation of the list as a (heap allocated) string 48 | fn stringify(&self) -> String { 49 | match *self { 50 | Cons(head, ref tail) => { 51 | // `format!` is similar to `print!`, but returns a heap 52 | // allocated string instead of printing to the console 53 | format!("{}, {}", head, tail.stringify()) 54 | }, 55 | Nil => { 56 | format!("Nil") 57 | }, 58 | } 59 | } 60 | } 61 | 62 | fn main() { 63 | // Create an empty linked list 64 | let mut list = List::new(); 65 | 66 | // Append some elements 67 | list = list.prepend(1); 68 | list = list.prepend(2); 69 | list = list.prepend(3); 70 | 71 | // Show the final state of the list 72 | println!("linked list has length: {}", list.len()); 73 | println!("{}", list.stringify()); 74 | } 75 | // linked list has length: 3 76 | // 3, 2, 1, Nil -------------------------------------------------------------------------------- /Chapter07/code/moving_closure.rs: -------------------------------------------------------------------------------- 1 | struct Block { 2 | number: i32 3 | } 4 | 5 | fn main() { 6 | let block = Block{ number:1 }; 7 | // ordinary closure: 8 | let closure = || { println!("n: {:?}", block.number); }; 9 | closure(); 10 | println!("n: {:?}", block.number); 11 | 12 | let block = Block{ number:1 }; 13 | // moving closure: 14 | // closure takes ownership of the block value 15 | let closure = move || {println!("n: {:?}", block.number); }; 16 | closure(); 17 | // error: use of moved value: `block.number` 18 | // println!("n: {:?}", block.number); 19 | } 20 | // n: 1 21 | // n: 1 22 | // n: 1 -------------------------------------------------------------------------------- /Chapter07/code/ownership1.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | n_tentacles: u32 4 | } 5 | 6 | fn main() { 7 | let mut klaatu = Alien{ planet: "Venus".to_string(), n_tentacles: 15 }; 8 | 9 | // a move of the resource: 10 | let kl2 = klaatu; 11 | // println!("{}", klaatu.planet); // use of moved value 'klaatu.planet' 12 | 13 | // let kl2 = transform(klaatu); // use of moved value: `klaatu` 14 | // println!("{}", klaatu.planet); // use of moved value 'klaatu.planet' 15 | // let klaatu = transform(klaatu); // use of moved value: `klaatu` 16 | // println!("{}", klaatu.planet); // Jupiter 17 | 18 | // a borrowing of the resource: 19 | // let kl2 = &klaatu; // a borrow or reference 20 | // let kl2 = &mut klaatu; // a mutable borrow or reference 21 | // kl2.n_tentacles = 14; 22 | // println!("{} - {}", kl2.planet, kl2.n_tentacles); // Venus - 14 23 | 24 | // ownership is transferred, original owner cannot access or change: 25 | // error: cannot assign to `klaatu.planet` because it is borrowed 26 | // klaatu.planet = "Pluto".to_string(); 27 | 28 | // error: cannot borrow `klaatu.planet` as immutable because `klaatu` is also borrowed as mutable 29 | // println!("{} - {}", klaatu.planet, klaatu.n_tentacles); 30 | } 31 | 32 | fn transform(a: Alien) -> Alien { 33 | Alien { planet:"Jupiter".to_string(), n_tentacles:0 } 34 | } 35 | // Venus - 14 36 | // Jupiter -------------------------------------------------------------------------------- /Chapter07/code/ownership2.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | n_tentacles: u32, 4 | } 5 | 6 | fn main() { 7 | let mut klaatu = Alien{ planet: "Venus".to_string(), n_tentacles: 15 }; 8 | 9 | { 10 | let kl2 = &mut klaatu; 11 | kl2.n_tentacles = 14; 12 | println!("{} - {}", kl2.planet, kl2.n_tentacles); // Venus - 14 13 | kl2.n_tentacles = 10; 14 | } 15 | 16 | // println!("{} - {}", kl2.planet, kl2.n_tentacles); // cannot find value `kl2` in this scope 17 | println!("{} - {}", klaatu.planet, klaatu.n_tentacles); // Venus - 10 18 | klaatu.planet = "Pluto".to_string(); 19 | println!("{} - {}", klaatu.planet, klaatu.n_tentacles); // Pluto - 10 20 | } -------------------------------------------------------------------------------- /Chapter07/code/ref.rs: -------------------------------------------------------------------------------- 1 | struct Magician { 2 | name: &'static str, 3 | power: u32 4 | } 5 | 6 | fn main() { 7 | let n = 42; 8 | match n { 9 | ref r => println!("Got a reference to {}", r), 10 | } 11 | 12 | let mut m = 42; 13 | match m { 14 | ref mut mr => { 15 | println!("Got a mutable reference to {}", mr); 16 | *mr = 43; 17 | }, 18 | } 19 | println!("m has changed to {}!", m); 20 | 21 | let mag = Magician { name: "Gandalf", power: 4625 }; 22 | let name = { 23 | // `ref_to_x` is a reference to the `x` field 24 | let Magician { name: ref ref_to_name, power: _ } = mag; 25 | // Return a copy of the `name` field of `mag` 26 | *ref_to_name 27 | }; 28 | println!("The magician's name is {}", name); 29 | } 30 | // Got a reference to 42 31 | // Got a mutable reference to 42 32 | // m has changed to 43! 33 | // The magician's name is Gandalf -------------------------------------------------------------------------------- /Chapter07/code/ref_count_notgood.rs: -------------------------------------------------------------------------------- 1 | // this program DOES NOT COMPILE: on purpose 2 | struct Alien { 3 | name: String, 4 | no_tentacles: u8 5 | } 6 | 7 | struct Tentacle { 8 | poison: u8, 9 | owner: Alien 10 | } 11 | 12 | fn main() { 13 | let dhark = Alien { name: "Dharkalen".to_string(), no_tentacles: 7 }; 14 | 15 | // defining dhark's tentacles: 16 | for i in 0u8..dhark.no_tentacles { 17 | // error in following line: 18 | // use of moved value 'dhark' 19 | // note: move occurs because `dhark` has type `Alien`, which does not implement the `Copy` trait 20 | // Tentacle { poison: i * 3, owner: dhark }; 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter07/code/refcount.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | 3 | #[derive(Debug)] 4 | struct Alien { 5 | name: String, 6 | n_tentacles: u8 7 | } 8 | 9 | #[derive(Debug)] 10 | struct Tentacle { 11 | poison: u8, 12 | owner: Rc 13 | } 14 | 15 | fn main() { 16 | let dhark = Alien { name: "Dharkalen".to_string(), n_tentacles: 7 }; 17 | 18 | let dhark_master = Rc::new(dhark); 19 | 20 | for i in 0u8..dhark_master.n_tentacles { 21 | // the clone() here copies the Rc pointer, not the Alien struct: 22 | let t = Tentacle { poison: i * 3, owner: dhark_master.clone() }; 23 | println!("{:?}", t); 24 | } 25 | } 26 | // Tentacle { poison: 0, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 27 | // Tentacle { poison: 3, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 28 | // Tentacle { poison: 6, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 29 | // Tentacle { poison: 9, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 30 | // Tentacle { poison: 12, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 31 | // Tentacle { poison: 15, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } 32 | // Tentacle { poison: 18, owner: Alien { name: "Dharkalen", n_tentacles: 7 } } -------------------------------------------------------------------------------- /Chapter07/code/references.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // immutable reference to immutable values: 3 | let n = 42i32; 4 | 5 | // a reference to n: 6 | let m = &n; 7 | println!("The address of n is {:p}", m); 8 | println!("The value of n is {}", *m); 9 | println!("The value of n is {}", m); 10 | 11 | let q = &42; 12 | println!("The square is: {}", square(q)); // 1764 13 | 14 | fn square(k: &i32) -> i32 { 15 | *k * *k 16 | } 17 | 18 | // references to immutable values are immutable: 19 | // *m = 7; // error: cannot assign to immutable borrowed content `*m` 20 | 21 | // multiple references to an immutable value: 22 | let o = &n; 23 | println!("The address of n is {:p}", o); 24 | println!("The value of n is {}", *o); 25 | 26 | // a mutable reference to an immutable value is not possible: 27 | // let m = &mut n; // error: cannot borrow immutable local variable `n` as mutable 28 | 29 | // references to mutable values: 30 | let mut u = 3.14f64; 31 | let v = &mut u; 32 | println!("The address of u is {:p}", v); 33 | println!("The value of u is {}", *v); 34 | *v = 3.15; 35 | println!("The value of u is now {}", *v); 36 | // error: cannot borrow `u` as immutable because it is also borrowed as mutable 37 | // println!("The value of u is {}", u); 38 | // u = u * 2.0; // error: cannot assign to `u` because it is borrowed 39 | 40 | // more than 1 mutable reference is not allowed: 41 | // let w = &mut u; // error: cannot borrow `u` as mutable more than once at a time 42 | 43 | // change a value by passing it as a reference to a function: 44 | let mut m = 7; 45 | add_three_to_magic(&mut m); 46 | println!("m is now {}", m); // 10 47 | } 48 | 49 | fn add_three_to_magic(num: &mut i32) { 50 | *num += 3; // value is changed in place with +=, is same as: *num = *num + 3 51 | } 52 | // The address of n is 0x7078eff8bc 53 | // The value of n is 42 54 | // The value of n is 42 55 | // The square is: 1764 56 | // The address of n is 0x7078eff8bc 57 | // The value of n is 42 58 | // The address of u is 0x7078effa38 59 | // The value of u is 3.14 60 | // The value of u is now 3.15 61 | // m is now 10 -------------------------------------------------------------------------------- /Chapter07/exercises/dangling_pointer.rs: -------------------------------------------------------------------------------- 1 | struct IntNumber<'a> { 2 | x: &'a i32, 3 | } 4 | 5 | fn main() { 6 | // n does not live long enough to be assigned to m 7 | // let m: &u32 = { 8 | // let n = &5u32; // error: borrowed value does not live long enough 9 | // n 10 | // }; 11 | // let o = *m; 12 | 13 | // The following will be rejected, since y has a shorter lifetime than x. 14 | let mut x = &3; 15 | { 16 | let mut y = 4; 17 | // x = &y; // error: `y` does not live long enough 18 | } // y is freed here, but x still lives... 19 | 20 | // 21 | let x = 1; // -+ x goes into scope 22 | // | 23 | { // | 24 | // let y = &5; // ---+ y goes into scope 25 | // let f = IntNumber { x: y }; // ---+ f goes into scope 26 | // x = &f.x; // | | error here 27 | } // ---+ f and y go out of scope 28 | // | 29 | println!("{}", x); // | 30 | } -------------------------------------------------------------------------------- /Chapter07/exercises/grow_a_tentacle.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | no_tentacles: u32, 4 | } 5 | 6 | fn main() { 7 | let mut klaatu = Alien{ planet: "Venus".to_string(), no_tentacles: 15 }; 8 | println!("Klaatu first has {} tentacles", klaatu.no_tentacles); // 15 9 | grow_a_tentacle(&mut klaatu); 10 | println!("Klaatu has now {} tentacles", klaatu.no_tentacles); // 16 11 | } 12 | 13 | fn grow_a_tentacle(al: &mut Alien) { 14 | al.no_tentacles += 1; 15 | } // al goes out of scope 16 | 17 | // Klaatu has first 15 tentacles 18 | // Klaatu has now 16 tentacles -------------------------------------------------------------------------------- /Chapter07/exercises/increment_vector.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let p = vec![1, 2, 3]; 3 | let q = increment(p); 4 | print!("new vector: "); 5 | for x in q { 6 | print!("{} ", x); 7 | } 8 | println!(""); 9 | 10 | let mut p = vec![1, 2, 3]; 11 | increment_mut(&mut p); 12 | print!("change in place: "); 13 | for x in p { 14 | print!("{} ", x); 15 | } 16 | } 17 | 18 | fn increment(mut v: Vec) -> Vec { 19 | for i in 0..v.len() { 20 | v[i] += 1; 21 | } 22 | v 23 | } 24 | 25 | fn increment_mut(v: &mut Vec) { 26 | for i in 0..v.len() { 27 | v[i] += 1; 28 | } 29 | } 30 | // new vector: 2 3 4 31 | // change in place: 2 3 4 -------------------------------------------------------------------------------- /Chapter07/exercises/ownership3.rs: -------------------------------------------------------------------------------- 1 | struct Alien { 2 | planet: String, 3 | no_tentacles: u32, 4 | } 5 | 6 | fn main() { 7 | let mut klaatu = Alien{ planet: "Venus".to_string(), no_tentacles: 15 }; 8 | 9 | // Question 1) 10 | // let kl2 = &klaatu; 11 | // error: cannot assign to immutable field `kl2.no_tentacles` 12 | // kl2.no_tentacles = 14; 13 | // println!("{} - {}", kl2.planet, kl2.no_tentacles); // Venus - 15 14 | 15 | // error: cannot assign to `klaatu.planet` because it is borrowed 16 | // klaatu.planet = "Pluto".to_string(); 17 | println!("{} - {}", klaatu.planet, klaatu.no_tentacles); // Venus - 15 18 | 19 | // Question 2) - with the following statement: 20 | // let klaatuc = klaatu; 21 | // let kl2 = &klaatu; 22 | // we get the following error at the kl2 binding: 23 | // error: use of moved value: `klaatu` 24 | // `klaatu` moved here (line 10: let klaatuc = klaatu;) 25 | // note: move occurs because `klaatu` has type `Alien`, which does not implement the `Copy` trait 26 | 27 | // mutability can be changed when ownership is transferred: 28 | let im = Box::new(7u32); 29 | // Mutability error: 30 | // error: cannot assign to immutable `Box` content `*im` 31 | // *im = 4; 32 | // Hand over the box, changing mutability 33 | let mut muta = im; 34 | println!("muta contains {}", muta); 35 | // println!("im contains {}", im); // error: use of moved value `im` 36 | // Modify the contents of the box 37 | *muta = 42; 38 | println!("muta now contains {}", muta); 39 | } 40 | // Venus - 15 41 | // muta contains 7 42 | // muta now contains 42 -------------------------------------------------------------------------------- /Chapter07/exercises/pointer_mutability.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // through the mutable pointer the value of x has been changed: 3 | let mut x = 5; 4 | increment(&mut x); 5 | println!("x is now {}", x); 6 | 7 | // borrowed references cannot inherit mutability: 8 | // mut borrowed means: the reference can change, but not its value! 9 | let mut val1 = 10; 10 | let mut val2 = 20; 11 | let mut borrowed = &val1; 12 | borrowed = &val2; 13 | // *borrowed = 11; // error: cannot assign to immutable borrowed content `*borrowed` 14 | 15 | // references are type checked: 16 | let mut val1 = 10; 17 | let mut val3 = 10.0; 18 | let mut borrowed = &val1; 19 | // error: mismatched types: 20 | // expected `&_`, found `&_` (expected integral variable, found floating-point variable) [E0308] 21 | // borrowed = &val3; 22 | } 23 | 24 | fn increment(r: &mut isize) { 25 | *r += 1; 26 | println!("r is now {}", *r); 27 | } 28 | // r is now 6 29 | // x is now 6 30 | -------------------------------------------------------------------------------- /Chapter08/code/builtin_macros.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let current_col = column!(); 3 | println!("defined on column: {}", current_col); 4 | 5 | let current_line = line!(); 6 | println!("defined on line: {}", current_line); 7 | 8 | let this_file = file!(); 9 | println!("defined in file: {}", this_file); 10 | 11 | not_ready(); 12 | } 13 | 14 | fn not_ready() { 15 | unimplemented!(); 16 | } 17 | // defined on column: 22 18 | // thread 'defined on line: 5 19 | // defined in file: F:\Rust\Rust book\The Rust Programming Language\Chapter 7 - Organizing code and macros\code\builtin_macros.rs 20 | //
' panicked at 'not yet implemented', F:\Rust\Rust book\The Rust Programming Language\Chapter 7 - Organizing code and macros\code\builtin_macros.rs:15 -------------------------------------------------------------------------------- /Chapter08/code/import_modules.rs: -------------------------------------------------------------------------------- 1 | mod modul1; 2 | mod modul2; 3 | 4 | // use modul1::func1; 5 | 6 | fn main() { 7 | modul1::func1(); 8 | modul2::func1(); 9 | 10 | // func1(); // error: unresolved name `func1` 11 | // func1(); // works when use modul1::func1; is added 12 | } 13 | // called func1 from modul1 14 | // called func1 from modul2 -------------------------------------------------------------------------------- /Chapter08/code/libmycrate.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter08/code/libmycrate.rlib -------------------------------------------------------------------------------- /Chapter08/code/libstructs.rlib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter08/code/libstructs.rlib -------------------------------------------------------------------------------- /Chapter08/code/macro_debug.rs: -------------------------------------------------------------------------------- 1 | #![feature(trace_macros)] 2 | #![feature(log_syntax)] 3 | 4 | macro_rules! vector { 5 | ( 6 | $x:expr,$($y:expr),* 7 | ) => ( 8 | println!("New argument: {}", $x); 9 | log_syntax!(vector!($($y),*)); 10 | ); 11 | ( $x:expr ) => ( 12 | println!("New argument: {}", $x); 13 | ) 14 | } 15 | 16 | fn main() { 17 | trace_macros!(true); 18 | vector!(1, 2, 3, 12); 19 | } -------------------------------------------------------------------------------- /Chapter08/code/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! welcome { 2 | // `()` indicates that the macro takes no argument 3 | () => ( 4 | // the macro will expand into the contents of this block 5 | println!("Welcome to the Game!"); 6 | ) 7 | } 8 | 9 | macro_rules! mac1 { 10 | ($arg:expr) => (println!("arg is {}", $arg)); 11 | } 12 | 13 | macro_rules! printall { 14 | ( $( $arg:expr ), * ) => ( {$( print!("{} / ", $arg) ); *} ); 15 | } 16 | 17 | macro_rules! create_fn { 18 | ($fname:ident) => ( 19 | fn $fname() { 20 | println!("Called the function {:?}()", stringify!($fname)) 21 | } 22 | ) 23 | } 24 | 25 | create_fn!(fn1); 26 | 27 | macro_rules! massert { 28 | ($arg:expr) => ( 29 | if $arg {} 30 | else { panic!("Assertion failed!"); } 31 | ); 32 | } 33 | 34 | macro_rules! unless { 35 | ($arg:expr, $branch:expr) => ( if !$arg { $branch }; ); 36 | } 37 | 38 | macro_rules! test_eq { 39 | ($name:ident, $left:expr, $right:expr) => { 40 | #[test] 41 | fn $name() { 42 | assert_eq!($left, $right); 43 | } 44 | } 45 | } 46 | 47 | test_eq!(seven_times_six_is_forty_two, 7 * 6, 42); 48 | test_eq!(seven_times_six_is_not_forty_three, 7 * 6, 43); 49 | 50 | fn main() { 51 | welcome!(); // Welcome to the Game! 52 | mac1!(42); // arg is 42 53 | mac1![42]; // arg is 42 54 | printall!("hello", 42, 3.14); // hello / 42 / 3.14 / 55 | fn1(); 56 | // massert!(1 == 42); // thread '
' panicked at 'Assertion failed!' 57 | let v = [10, 40, 30]; 58 | massert!(v.contains(&30)); 59 | massert!(!v.contains(&50)); 60 | unless!(v.contains(&25), println!("v does not contain 25")); 61 | 62 | } 63 | // Welcome to the Game! 64 | // arg is 42 65 | // arg is 42 66 | // hello / 42 / 3.14 / Called the function "fn1"() 67 | // v does not contain 25 -------------------------------------------------------------------------------- /Chapter08/code/mod_private.rs: -------------------------------------------------------------------------------- 1 | mod library { 2 | pub struct Interface { 3 | m_impl: Impl // private field 4 | } 5 | 6 | impl Interface { 7 | pub fn new() -> Interface { 8 | Interface{ m_impl: Impl } 9 | } 10 | 11 | pub fn f(&self){ 12 | self.m_impl.f(); 13 | } 14 | } 15 | 16 | struct Impl; 17 | 18 | impl Impl { 19 | fn f(&self){ // private method 20 | println!("f"); 21 | } 22 | } 23 | } 24 | 25 | fn main() { 26 | let o = library::Interface::new(); 27 | o.f(); 28 | } 29 | // f -------------------------------------------------------------------------------- /Chapter08/code/modul1/mod.rs: -------------------------------------------------------------------------------- 1 | pub fn func1() { 2 | println!("called func1 from modul1"); 3 | } 4 | -------------------------------------------------------------------------------- /Chapter08/code/modul2.rs: -------------------------------------------------------------------------------- 1 | pub fn func1() { 2 | println!("called func1 from modul2"); 3 | } -------------------------------------------------------------------------------- /Chapter08/code/modules.rs: -------------------------------------------------------------------------------- 1 | use game1::func2; 2 | use game1::func2 as gf2; 3 | // use game1::{func2, func3}; 4 | // pub use game1::{func2, func3}; // visible in the super level 5 | // use game1::*; 6 | use game1::subgame1::subfunc1 as sf1; 7 | 8 | mod game1 { 9 | // all of the module's code items go in here 10 | fn func1() { // private function 11 | println!("Am I visible?"); 12 | } 13 | 14 | pub fn func2() { 15 | println!("You called func2 in game1!"); 16 | } 17 | 18 | pub fn func3() { 19 | println!("You called func3 in game1!"); 20 | } 21 | 22 | pub mod subgame1 { 23 | pub fn subfunc1() { 24 | println!("You called subfunc1 in subgame1!"); 25 | } 26 | } 27 | 28 | pub struct Magician { 29 | pub name: String, 30 | pub age: i32, 31 | power: i32 32 | } 33 | } 34 | 35 | fn main() { 36 | // game1::func1(); // error: function `func1` is private 37 | game1::func2(); // works without the use import 38 | self::game1::func2(); 39 | ::game1::func2(); 40 | // super::game1::func2(); // unresolved name 41 | 42 | // calling a nested module: 43 | game1::subgame1::subfunc1(); 44 | 45 | // importing a function or module with use: 46 | func2(); 47 | gf2(); 48 | sf1(); 49 | 50 | // error[E0451]: field `power` of struct `game1::Magician` is private 51 | // let mag1 = game1::Magician { name: "Gandalf".to_string(), age: 725, power: 98}; 52 | } 53 | 54 | // You called func2 in game1! 55 | // You called subfunc1 in subgame1! 56 | // You called func2 in game1! 57 | // You called func2 in game1! 58 | // You called subfunc1 in subgame1! -------------------------------------------------------------------------------- /Chapter08/code/monsters/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Chapter08/code/monsters/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "monsters" 4 | version = "0.0.1" 5 | authors = ["Ivo Balbaert "] 6 | 7 | [dependencies] 8 | log = "0.3.1" 9 | mac = "*" -------------------------------------------------------------------------------- /Chapter08/code/monsters/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn print_from_monsters() { 2 | println!("Printing from crate monsters!"); 3 | } 4 | 5 | pub trait Monster { 6 | fn new(hlt: u32, dam: u32) -> Self; 7 | 8 | fn attack(&self); 9 | fn noise(&self) -> &'static str; 10 | 11 | fn attacks_with_sound(&self) { 12 | println!("The Monster attacks by making an awkward sound {}", self.noise()); 13 | } 14 | } 15 | 16 | #[derive(Debug)] 17 | pub struct Zombie { pub health: u32, pub damage: u32 } 18 | 19 | impl Monster for Zombie { 20 | fn new(mut h: u32, d: u32) -> Zombie { 21 | // constraints: 22 | if h > 100 { h = 100; } 23 | Zombie {health: h, damage: d} 24 | } 25 | 26 | fn attack(&self) { 27 | println!("The Zombie bites! Your health lowers with {} damage points.", 2 * self.damage); 28 | } 29 | 30 | fn noise(&self) -> &'static str { 31 | "Aaargh!" 32 | } 33 | } 34 | 35 | struct Alien { health: u32, damage: u32 } 36 | 37 | impl Monster for Alien { 38 | fn new(mut h: u32, d: u32) -> Alien { 39 | // constraints: 40 | if h > 100 { h = 100; } 41 | Alien {health: h, damage: d} 42 | } 43 | 44 | fn attack(&self) { 45 | println!("I attack! Your health lowers with {} damage points.", self.damage); 46 | } 47 | 48 | fn noise(&self) -> &'static str { 49 | "Shriek!" 50 | } 51 | } 52 | 53 | struct Predator { health: u32, damage: u32 } 54 | // Predator still has to implement new and noise methods: 55 | // impl Monster for Predator { 56 | // fn attack(&self) { 57 | // println!("I bite you! Your health lowers with {} damage points.", 3 * self.damage); 58 | // } 59 | // } -------------------------------------------------------------------------------- /Chapter08/code/monsters/src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate log; 3 | extern crate mac; 4 | 5 | extern crate monsters; 6 | use monsters::Monster; // import the trait 7 | 8 | fn main() { 9 | monsters::print_from_monsters(); 10 | let zmb1 = monsters::Zombie {health: 75, damage: 15}; 11 | println!("Oh no, I hear: {}", zmb1.noise()); 12 | zmb1.attack(); 13 | println!("{:?}", zmb1); 14 | 15 | info!("Gathering information from monster {:?}", zmb1); 16 | } 17 | // Printing from crate monsters! 18 | // Oh no, I hear: Aaargh! 19 | // The Zombie bites! Your health lowers with 30 damage points. 20 | // Zombie { health: 75, damage: 15 } -------------------------------------------------------------------------------- /Chapter08/code/random/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /Chapter08/code/random/Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "random" 3 | version = "0.0.1" 4 | dependencies = [ 5 | "rand 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", 6 | ] 7 | 8 | [[package]] 9 | name = "bitflags" 10 | version = "0.7.0" 11 | source = "registry+https://github.com/rust-lang/crates.io-index" 12 | 13 | [[package]] 14 | name = "conv" 15 | version = "0.3.3" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | dependencies = [ 18 | "custom_derive 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 19 | ] 20 | 21 | [[package]] 22 | name = "custom_derive" 23 | version = "0.1.7" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | 26 | [[package]] 27 | name = "libc" 28 | version = "0.2.28" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | 31 | [[package]] 32 | name = "magenta" 33 | version = "0.1.1" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | dependencies = [ 36 | "conv 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", 37 | "magenta-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 38 | ] 39 | 40 | [[package]] 41 | name = "magenta-sys" 42 | version = "0.1.1" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | dependencies = [ 45 | "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", 46 | ] 47 | 48 | [[package]] 49 | name = "rand" 50 | version = "0.3.16" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | dependencies = [ 53 | "libc 0.2.28 (registry+https://github.com/rust-lang/crates.io-index)", 54 | "magenta 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 55 | ] 56 | 57 | [metadata] 58 | "checksum bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d" 59 | "checksum conv 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "78ff10625fd0ac447827aa30ea8b861fead473bb60aeb73af6c1c58caf0d1299" 60 | "checksum custom_derive 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "ef8ae57c4978a2acd8b869ce6b9ca1dfe817bff704c220209fdef2c0b75a01b9" 61 | "checksum libc 0.2.28 (registry+https://github.com/rust-lang/crates.io-index)" = "bb7b49972ee23d8aa1026c365a5b440ba08e35075f18c459980c7395c221ec48" 62 | "checksum magenta 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4bf0336886480e671965f794bc9b6fce88503563013d1bfb7a502c81fe3ac527" 63 | "checksum magenta-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "40d014c7011ac470ae28e2f76a02bfea4a8480f73e701353b49ad7a8d75f4699" 64 | "checksum rand 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "eb250fd207a4729c976794d03db689c9be1d634ab5a1c9da9492a13d8fecbcdf" 65 | -------------------------------------------------------------------------------- /Chapter08/code/random/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "random" 4 | version = "0.0.1" 5 | authors = ["Ivo Balbaert "] 6 | 7 | [dependencies] 8 | rand = "*" -------------------------------------------------------------------------------- /Chapter08/code/random/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | use rand::Rng; 3 | 4 | fn main() { 5 | println!("Give me 5 random numbers:"); 6 | for _ in 0..5 { 7 | let rnd = rand::random::(); 8 | print!("{} / ", rnd); 9 | } 10 | println!(""); 11 | println!("Give me 5 positive random numbers smaller than 32:"); 12 | for _ in 0..5 { 13 | let rnd = (rand::random::() % 32) + 1; 14 | print!("{} / ", rnd); 15 | } 16 | println!(""); 17 | 18 | let mut rng = rand::thread_rng(); 19 | if rng.gen() { // random bool 20 | println!("i32: {}, u32: {}", rng.gen::(), rng.gen::()) 21 | } 22 | 23 | // generate a random number in a range, for example: 1 - 100: 24 | let secret_number = rand::thread_rng().gen_range(1, 101); 25 | println!("The secret number is: {}", secret_number); 26 | 27 | let tuple = rand::random::<(f64, char)>(); 28 | println!("{:?}", tuple); 29 | 30 | // generate a random string: 31 | let mut str = String::new(); 32 | for _ in 0..10 { 33 | str.push(rand::random::() as char); 34 | } 35 | println!("{:?}", str); 36 | 37 | } 38 | // Give me 5 random numbers: 39 | // -1786096291 / -312872251 / 959357270 / 1391515785 / -1379700184 / 40 | // Give me 5 positive random numbers smaller than 32: 41 | // 11 / 15 / 28 / 13 / 23 / 42 | // The secret number is: 16 43 | // (0.279622, '\u{583cf}') 44 | // "n\u{1b}\u{8a}\u{98}\"\u{d2}c\u{ee}\u{a8}I" -------------------------------------------------------------------------------- /Chapter08/code/structs.rs: -------------------------------------------------------------------------------- 1 | #![crate_type = "lib"] 2 | #![crate_name = "mycrate"] 3 | 4 | struct Player { 5 | nname: &'static str, // nickname 6 | health: i32, 7 | level: u8 8 | } 9 | 10 | struct Scoreu; // unit struct 11 | struct Kilograms(u32); 12 | struct Score(i32, u8); 13 | 14 | fn demo() { 15 | let score1 = Score(73, 2); // make (instantiate) a tuple struct 16 | let Score(h, l) = score1; // // extract values by destructuring 17 | println!("Health {} - Level {}", h, l); 18 | 19 | // newtype: 20 | let weight = Kilograms(250); 21 | let Kilograms(kgm) = weight; // extracting kgm 22 | println!("weight is {} kilograms", kgm); 23 | 24 | // struct: 25 | let mut pl1 = Player{nname: "Dzenan", health: 73, level: 2}; 26 | println!("Player {} is at level {}", pl1.nname, pl1.level); 27 | pl1.level = 3; 28 | 29 | // pointers do automatic dereferencing when accessing data structure elements: 30 | let ps = &Player{ nname: "John", health: 95, level: 1 }; 31 | println!("{} == {}", ps.nname, (*ps).nname); 32 | 33 | // destructuring a struct: 34 | let Player{health: ht, nname: nn, ..} = pl1; 35 | println!("Player {} has health {}", nn, ht); 36 | } 37 | -------------------------------------------------------------------------------- /Chapter08/code/unimplemented.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | unimplemented!(); 3 | } -------------------------------------------------------------------------------- /Chapter08/code/unreachable.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | if false { 3 | unreachable!(); 4 | } 5 | unreachable!(); 6 | } -------------------------------------------------------------------------------- /Chapter08/exercises/macro_ex.rs: -------------------------------------------------------------------------------- 1 | macro_rules! mac2 { 2 | ($arg:expr) => (3 * $arg); 3 | } 4 | 5 | macro_rules! mac3 { 6 | ($arg:ident) => (let $arg = 42); 7 | } 8 | 9 | macro_rules! mac4 { 10 | ($arg:expr) => ( { 11 | print!("start - "); 12 | print!("{} - ", $arg); 13 | print!("end"); 14 | }); 15 | } 16 | 17 | macro_rules! says { 18 | ($x:expr) => { 19 | println!("He/She says: '{}'", $x); 20 | }; 21 | ($x:expr, $y:expr) => { 22 | println!("He/She says: '{}' to {}", $x, $y); 23 | }; 24 | } 25 | 26 | 27 | fn main() { 28 | println!("{}", mac2!(5)); // 15 29 | println!("{}", mac2!(2 + 3)); // 15 30 | mac3!(x); // expands into let x = 42; 31 | println!("{}", x); // 42 32 | mac4!("Where am I?"); // start - Where am I? - end 33 | println!(""); 34 | says!("Hi"); 35 | says!("Hi", "Jim"); 36 | } 37 | // 15 38 | // 15 39 | // 42 40 | // start - Where am I? - end 41 | // He/She says: 'Hi' 42 | // He/She says: 'Hi' to Jim -------------------------------------------------------------------------------- /Chapter08/exercises/priv_struct.rs: -------------------------------------------------------------------------------- 1 | use game1::Magician; 2 | 3 | mod game1 { 4 | #[derive(Debug)] 5 | pub struct Magician { 6 | pub name: String, 7 | pub age: i32, 8 | power: i32 9 | } 10 | 11 | impl Magician { 12 | // A public constructor 13 | pub fn new(nm: String, ag: i32, pow: i32) -> Magician { 14 | Magician { name: nm, age: ag, power: pow} 15 | } 16 | } 17 | } 18 | 19 | fn main() { 20 | // error: field `power` of struct `game1::Magician` is private 21 | // let mag1 = game1::Magician { name: "Gandalf", age: 725, power: 98}; 22 | 23 | let mag1 = Magician::new("Gandalf".to_string(), 725, 98); 24 | println!("I just made a magician {:?}", mag1); 25 | } 26 | // I just made a magician Magician { name: "Gandalf", age: 725, power: 98 } -------------------------------------------------------------------------------- /Chapter09/code/change_vec.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::{Arc, Mutex}; 3 | 4 | fn main() { 5 | let mut magicians = Arc::new(Mutex::new(vec!["Morgan".to_string(), 6 | "Allanon".to_string(), "Jafar".to_string()])); 7 | 8 | for i in 0..3 { 9 | let magicians = magicians.clone(); 10 | thread::spawn(move || { 11 | let mut mags = magicians.lock(); 12 | match mags { 13 | Ok(mut mags) => 14 | { 15 | let mut temp = mags[i].to_string(); 16 | temp.push_str("ius"); 17 | mags[i] = temp; 18 | }, 19 | Err(str) => println!("{}", str) 20 | } 21 | }).join(); 22 | } 23 | println!("{:?} - ", *magicians); 24 | print!("{:?} - ", *magicians.lock().unwrap()); 25 | } 26 | // Mutex { data: ["Morganius", "Allanonius", "Jafarius"] } - [Finished in 29.6s] 27 | // ["Morganius", "Allanonius", "Jafarius"] -------------------------------------------------------------------------------- /Chapter09/code/channel_box.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::mpsc; 3 | 4 | trait Message : Send { 5 | fn print(&self); 6 | } 7 | 8 | struct Msg1 { 9 | value: i32 10 | } 11 | 12 | impl Message for Msg1 { 13 | fn print(&self) { 14 | println!("value: {:?}", self.value); 15 | } 16 | } 17 | 18 | fn main() { 19 | let (tx, rx) = mpsc::channel::>(); 20 | 21 | let handle = thread::spawn(move|| { 22 | let msg = rx.recv().unwrap(); 23 | msg.print(); 24 | }); 25 | 26 | let msg = Box::new(Msg1{ value:1 }); 27 | tx.send(msg).unwrap(); 28 | 29 | handle.join().ok(); 30 | } 31 | // value: 1 -------------------------------------------------------------------------------- /Chapter09/code/channels.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::mpsc::channel; 3 | // use std::sync::mpsc::{Sender, Receiver}; 4 | 5 | fn main() { 6 | // let (tx, rx): (Sender, Receiver) = mpsc::channel(); 7 | let (tx, rx) = channel(); 8 | 9 | thread::spawn(move|| { 10 | // tx.send(10).unwrap(); 11 | tx.send(10).ok().expect("Unable to send message"); 12 | }); 13 | 14 | let res = rx.recv().unwrap(); 15 | println!("{:?}", res); // 10 16 | } 17 | // 10 -------------------------------------------------------------------------------- /Chapter09/code/channels2.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::mpsc::channel; 3 | 4 | fn main() { 5 | let (tx, rx) = channel(); 6 | 7 | thread::spawn(move|| { 8 | let result = some_expensive_computation(); 9 | tx.send(result).ok().expect("Unable to send message"); 10 | }); 11 | 12 | some_other_expensive_computation(); 13 | let result = rx.recv(); 14 | println!("{:?}", result); // Ok(1) 15 | } 16 | 17 | fn some_expensive_computation() -> i32 { 1 } 18 | fn some_other_expensive_computation() { } -------------------------------------------------------------------------------- /Chapter09/code/channels_struct.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::mpsc::channel; 3 | 4 | struct Block { 5 | value: i32 6 | } 7 | 8 | fn main() { 9 | let (tx1, rx1) = channel::(); 10 | let (tx2, rx2) = channel::(); 11 | 12 | thread::spawn(move|| { 13 | let mut block = rx1.recv().unwrap(); 14 | println!("Input: {:?}", block.value); 15 | 16 | block.value += 1; 17 | tx2.send(block).unwrap(); 18 | }); 19 | 20 | let input = Block{ value: 1 }; 21 | tx1.send(input).unwrap(); 22 | 23 | let output = rx2.recv().unwrap(); 24 | println!("Output: {:?}", output.value); 25 | } 26 | // Input: 1 27 | // Output: 2 -------------------------------------------------------------------------------- /Chapter09/code/make_channel.rs: -------------------------------------------------------------------------------- 1 | use std::sync::mpsc::Receiver; 2 | use std::sync::mpsc::channel; 3 | 4 | fn make_chan() -> Receiver { 5 | let (tx, rx) = channel(); 6 | tx.send(7).unwrap(); 7 | rx 8 | } 9 | 10 | fn main() { 11 | let rx = make_chan(); 12 | if let Some(msg) = rx.recv().ok() { 13 | println!("received message {}", msg); 14 | }; 15 | } 16 | // received message 7 -------------------------------------------------------------------------------- /Chapter09/code/many_threads.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::time; 3 | 4 | static NTHREADS: i32 = 10000; 5 | 6 | fn main() { 7 | println!("************************** Before the start of the threads"); 8 | for i in 0..NTHREADS { 9 | thread::spawn(move || { 10 | println!("this is thread number {}", i) 11 | }); 12 | } 13 | thread::sleep(time::Duration::from_millis(500)); 14 | println!("************************** All threads finished!"); 15 | } -------------------------------------------------------------------------------- /Chapter09/code/many_threads/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /Chapter09/code/many_threads/Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "many_threads" 3 | version = "0.1.0" 4 | dependencies = [ 5 | "num_cpus 1.6.2 (registry+https://github.com/rust-lang/crates.io-index)", 6 | "threadpool 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)", 7 | ] 8 | 9 | [[package]] 10 | name = "libc" 11 | version = "0.2.29" 12 | source = "registry+https://github.com/rust-lang/crates.io-index" 13 | 14 | [[package]] 15 | name = "num_cpus" 16 | version = "1.6.2" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | dependencies = [ 19 | "libc 0.2.29 (registry+https://github.com/rust-lang/crates.io-index)", 20 | ] 21 | 22 | [[package]] 23 | name = "threadpool" 24 | version = "1.5.0" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | dependencies = [ 27 | "num_cpus 1.6.2 (registry+https://github.com/rust-lang/crates.io-index)", 28 | ] 29 | 30 | [metadata] 31 | "checksum libc 0.2.29 (registry+https://github.com/rust-lang/crates.io-index)" = "8a014d9226c2cc402676fbe9ea2e15dd5222cd1dd57f576b5b283178c944a264" 32 | "checksum num_cpus 1.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aec53c34f2d0247c5ca5d32cca1478762f301740468ee9ee6dcb7a0dd7a0c584" 33 | "checksum threadpool 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cd329bef8c4b6c60ce9f0b4e12813feb0f1b71b16cc56dc9773be77e3b8d9294" 34 | -------------------------------------------------------------------------------- /Chapter09/code/many_threads/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "many_threads" 3 | version = "0.1.0" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [dependencies] 7 | num_cpus = "*" 8 | threadpool = "*" 9 | 10 | -------------------------------------------------------------------------------- /Chapter09/code/many_threads/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate num_cpus; 2 | extern crate threadpool; 3 | 4 | use std::thread; 5 | use std::time; 6 | use threadpool::ThreadPool; 7 | 8 | fn main() { 9 | let ncpus = num_cpus::get(); 10 | println!("The number of cpus in this machine is: {}", ncpus); 11 | 12 | let pool = ThreadPool::new(ncpus); 13 | 14 | for i in 0..ncpus { 15 | pool.execute(move || { 16 | println!("this is thread number {}", i) 17 | }); 18 | } 19 | 20 | thread::sleep(time::Duration::from_millis(50)); 21 | } 22 | // The number of cpus in this machine is: 8 23 | // for example (output can change each run) 24 | // this is thread number 0 25 | // this is thread number 5 26 | // this is thread number 7 27 | // this is thread number 3 28 | // this is thread number 4 29 | // this is thread number 1 30 | // this is thread number 6 31 | // this is thread number 2 -------------------------------------------------------------------------------- /Chapter09/code/moving_closure.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | fn main() { 4 | read(); 5 | } 6 | 7 | fn read() { 8 | let book = read_book("book1.txt"); 9 | // error: closure may outlive the current function, but it borrows `book`, 10 | // which is owned by the current function 11 | // thread::spawn(|| { 12 | // println!("{:?}", book); 13 | // }); 14 | 15 | thread::spawn(move || { 16 | println!("{:?}", book); 17 | }); 18 | } 19 | 20 | fn read_book(s: &str) { } 21 | 22 | // () -------------------------------------------------------------------------------- /Chapter09/code/not_shared.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::time; 3 | 4 | fn main() { 5 | let mut health = 12; 6 | for i in 2..5 { 7 | thread::spawn(move || { 8 | health *= i; 9 | }); 10 | } 11 | thread::sleep(time::Duration::from_secs(2)); 12 | println!("{}", health); // 12 13 | } -------------------------------------------------------------------------------- /Chapter09/code/panic_thread.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | fn main() { 4 | let result = thread::spawn(move || { 5 | panic!("I have fallen into an unrecoverable trap!"); 6 | }).join(); 7 | 8 | if result.is_err() { 9 | println!("This child has panicked"); 10 | } 11 | } 12 | // thread '' panicked at 'I have fallen into an unrecoverable trap!' 13 | // This child has panicked 14 | -------------------------------------------------------------------------------- /Chapter09/code/sync_channel.rs: -------------------------------------------------------------------------------- 1 | use std::sync::mpsc::sync_channel; 2 | use std::thread; 3 | use std::time; 4 | 5 | type TokenType = i32; 6 | 7 | struct Msg { 8 | typ: TokenType, 9 | val: String, 10 | } 11 | 12 | fn main() { 13 | let (tx, rx) = sync_channel(1); // buffer size 1 14 | tx.send(Msg {typ: 42, val: "Rust is cool".to_string()}).unwrap(); 15 | println!("message 1 is sent"); 16 | thread::spawn(move|| { 17 | tx.send(Msg {typ: 43, val: "Rust is still cool".to_string()}).unwrap(); 18 | println!("message 2 is sent"); 19 | }); 20 | 21 | println!("Waiting for 3 seconds ..."); 22 | thread::sleep(time::Duration::from_secs(3)); 23 | 24 | if let Some(msg) = rx.recv().ok() { 25 | println!("received message of type {} and val {}", msg.typ, msg.val); 26 | }; 27 | if let Some(msg) = rx.recv().ok() { 28 | println!("received second message of type {} and val {}", msg.typ, msg.val); 29 | }; 30 | } 31 | // message 1 is sent 32 | // Waiting for 3 seconds ... 33 | // received message of type 42 and val Rust is cool 34 | // message 2 is sent 35 | // received second message of type 43 and val Rust is still cool 36 | -------------------------------------------------------------------------------- /Chapter09/code/thread_safe.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::{Arc, Mutex}; 3 | 4 | fn main() { 5 | let mut health = 12; 6 | println!("health before: {:?}", health); 7 | let data = Arc::new(Mutex::new(health)); 8 | for i in 2..5 { 9 | let mutex = data.clone(); 10 | thread::spawn(move || { 11 | let health = mutex.lock(); 12 | match health { 13 | // health is multiplied by i: 14 | Ok(mut health) => *health *= i, 15 | Err(str) => println!("{}", str) 16 | } 17 | }).join(); 18 | }; 19 | health = *data.lock().unwrap(); 20 | println!("health after: {:?}", health); 21 | } 22 | // health before: 12 23 | // health after: 288 24 | // because: 288 = 12 * 2 * 3 * 4 -------------------------------------------------------------------------------- /Chapter09/code/thread_spawn.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::time; 3 | 4 | fn main() { 5 | let handle = thread::spawn(move || { 6 | println!("Hello from the goblin in the spawned thread!"); 7 | }); 8 | 9 | thread::sleep(time::Duration::from_millis(50)); 10 | 11 | // do other work in the meantime 12 | 13 | // wait on child thread to end 14 | let output = handle.join().unwrap(); // () 15 | println!("{:?}", output); 16 | 17 | // wait on child thread, if no other work has to be done: 18 | thread::spawn(move || { 19 | println!("Hello again from the goblin in the spawned thread!"); 20 | // other work done in child thread 21 | }).join(); 22 | 23 | let child = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn(move || { 24 | // code to be executed in thread 25 | }).unwrap(); 26 | 27 | } 28 | // Hello from the goblin in the spawned thread! 29 | // () 30 | // Hello again from the goblin in the spawned thread! 31 | -------------------------------------------------------------------------------- /Chapter09/exercises/exc_thread_safe.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::{Arc, Mutex}; 3 | 4 | fn main() { 5 | let data = Arc::new(Mutex::new( vec![7, 13, 42] )); 6 | (0..3).map(|i| { 7 | let mutex = data.clone(); 8 | thread::spawn(move || { 9 | let mut vec = mutex.lock().unwrap(); 10 | vec[i] *= 3; 11 | }).join() 12 | }).collect::>(); 13 | println!("{:?}", *data.lock().unwrap()); 14 | } 15 | // [21, 39, 126] 16 | -------------------------------------------------------------------------------- /Chapter09/exercises/shared_channel.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::sync::mpsc; 3 | 4 | static NTHREADS: usize = 8; 5 | 6 | fn main() { 7 | let (tx, rx) = mpsc::channel(); 8 | 9 | for id in 0..NTHREADS { 10 | let thread_tx = tx.clone(); // clone the sender end-point 11 | thread::spawn(move || { 12 | thread_tx.send(id).unwrap(); 13 | println!("thread {} done", id); 14 | }); 15 | } 16 | 17 | let mut ids = Vec::with_capacity(NTHREADS); 18 | for _ in 0..NTHREADS { 19 | ids.push(rx.recv().unwrap()); 20 | } 21 | 22 | println!("{:?}", ids); 23 | } 24 | // -- The order is different each time the program is run: -- 25 | // thread 0 done 26 | // thread 4 done 27 | // thread 1 done 28 | // thread 5 done 29 | // thread 7 done 30 | // thread 2 done 31 | // thread 3 done 32 | // thread 6 done 33 | // [6, 1, 0, 4, 5, 7, 2, 3] -------------------------------------------------------------------------------- /Chapter10/code/asm.rs: -------------------------------------------------------------------------------- 1 | // error: use of unstable library feature 'asm' 2 | // help: add #![feature(asm)] to the crate attributes to enable 3 | #![feature(asm)] 4 | 5 | fn subtract(a: i32, b: i32) -> i32 { 6 | let sub: i32; 7 | unsafe { 8 | asm!("sub $2, $1; mov $1, $0" 9 | : "=r"(sub) 10 | : "r"(a), "r"(b) 11 | ); 12 | } 13 | sub 14 | } 15 | 16 | fn main() { 17 | println!("{}", subtract(42, 7)) // 35 18 | } -------------------------------------------------------------------------------- /Chapter10/code/calling_clibrary.0.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter10/code/calling_clibrary.0.o -------------------------------------------------------------------------------- /Chapter10/code/calling_clibrary.crate.allocator.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter10/code/calling_clibrary.crate.allocator.o -------------------------------------------------------------------------------- /Chapter10/code/calling_clibrary.crate.metadata.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Essentials-Second-Edition/b638efc67450e670c36afde1ee9df9974500de38/Chapter10/code/calling_clibrary.crate.metadata.o -------------------------------------------------------------------------------- /Chapter10/code/calling_clibrary.rs: -------------------------------------------------------------------------------- 1 | #[repr(C)] 2 | #[derive(Copy, Clone, Debug)] 3 | struct Complex { 4 | re: f32, 5 | im: f32, 6 | } 7 | 8 | #[link(name = "m")] 9 | extern { 10 | fn ctanf(z: Complex) -> Complex; 11 | } 12 | 13 | fn tan(z: Complex) -> Complex { 14 | unsafe { ctanf(z) } 15 | } 16 | 17 | fn main() { 18 | let z = Complex { re: -1., im: 1. }; // z is -1 + i 19 | let z_tan = tan(z); 20 | println!("the tangents of {:?} is {:?}", z, z_tan); 21 | } 22 | // the tangents of Complex { re: -1, im: 1 } is Complex { re: -0.271753, im: 1.083923 } -------------------------------------------------------------------------------- /Chapter10/code/calling_libc.rs: -------------------------------------------------------------------------------- 1 | #![feature(libc)] // only for use on the nightly release 2 | extern crate libc; 3 | use libc::puts; 4 | use std::ffi::CString; 5 | 6 | fn main() { 7 | let sentence = "Merlin is the greatest magician!"; 8 | let to_print = CString::new(sentence).unwrap(); 9 | unsafe { 10 | puts(to_print.as_ptr()); 11 | } 12 | } 13 | // Merlin is the greatest magician! -------------------------------------------------------------------------------- /Chapter10/code/parsing_argument.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | if let Some(arg1) = std::env::args().nth(1) { 3 | if let Ok(x) = arg1.parse::() { 4 | println!("Got it: {}", x); 5 | } else { 6 | println!("I wasn't given an integer!"); 7 | } 8 | } else { 9 | println!("I wasn't given an argument!"); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter10/code/pointer_offset.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let items = [1u32, 2, 3, 4]; 3 | let ptr = &items[1] as *const u32; 4 | println!("{}", unsafe { *ptr }); 5 | println!("{}", unsafe { *ptr.offset(-1) }); 6 | println!("{}", unsafe { *ptr.offset(1) }); 7 | // error: binary operation `+` cannot be applied to type `*const u32` [E0369] 8 | // println!("{}", unsafe { ptr + 2}); 9 | } 10 | // 2 11 | // 1 12 | // 3 13 | -------------------------------------------------------------------------------- /Chapter10/code/raw_pointers.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // dereferencing a raw pointer: 3 | let p_raw: *const u32 = &10; 4 | // error: dereference of unsafe pointer requires unsafe function or block [E0133] 5 | // let n = *p_raw; 6 | 7 | unsafe { 8 | // dereferencing a raw pointer must be done inside unsafe block: 9 | let n = *p_raw; 10 | println!("{}", n); // 10 11 | } 12 | 13 | // converting between references and raw pointers: 14 | let gr: f32 = 1.618; 15 | let p_imm: *const f32 = &gr as *const f32; // explicit cast 16 | let mut m: f32 = 3.14; 17 | let p_mut: *mut f32 = &mut m; // implicit coercion 18 | 19 | unsafe { 20 | let ref_imm: &f32 = &*p_imm; 21 | let ref_mut: &mut f32 = &mut *p_mut; 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter10/code/size_of_val.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | fn main() { 4 | let arr = ["Rust", "Go", "Swift"]; 5 | println!("array arr occupies {} bytes", mem::size_of_val(&arr)); 6 | println!("The size of an isize: {} bytes", mem::size_of::()); 7 | } 8 | // array arr occupies 48 bytes 9 | // The size of an isize: 8 bytes -------------------------------------------------------------------------------- /Chapter10/code/swap.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | fn main() { 4 | let mut n = 0; 5 | let mut m = 1; 6 | mem::swap(&mut n, &mut m); 7 | println!("n: {} m: {}", n, m); 8 | } 9 | // n: 1 m: 0 10 | -------------------------------------------------------------------------------- /Chapter10/code/unsafe.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | static mut N: i32 = 42; 4 | 5 | fn main() { 6 | let v: &[u8] = unsafe { 7 | mem::transmute("Gandalf") 8 | }; 9 | println!("{:?}", v); 10 | 11 | // N = 108; // use of mutable static requires unsafe function or block 12 | // reading or changing a static mutable variable: 13 | unsafe { 14 | println!("{:?}", N ); // 42 15 | N = 108; 16 | println!("{:?}", N ); // 108 17 | } 18 | } 19 | // [71, 97, 110, 100, 97, 108, 102] 20 | // 42 21 | // 108 -------------------------------------------------------------------------------- /Chapter11/code/a/b.txt: -------------------------------------------------------------------------------- 1 | hello -------------------------------------------------------------------------------- /Chapter11/code/hashmaps.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | fn main() { 4 | let mut monsters = HashMap::new(); 5 | 6 | monsters.insert("Oron", "Uranus"); 7 | monsters.insert("Cyclops", "Venus"); 8 | monsters.insert("Rahav", "Neptune"); 9 | monsters.insert("Homo Sapiens", "Earth"); 10 | 11 | match monsters.get(&"Rahav") { 12 | Some(&planet) => println!("Rahav originates from: {}", planet), 13 | _ => println!("Planet of Rahav unknown."), 14 | } 15 | 16 | monsters.remove(&("Homo Sapiens")); 17 | 18 | // `HashMap::iter()` returns 19 | for (monster, planet) in monsters.iter() { 20 | println!("Monster {} originates from planet {}", monster, planet); 21 | } 22 | } 23 | // Rahav originates from: Neptune 24 | // Monster Rahav originates from planet Neptune 25 | // Monster Cyclops originates from planet Venus 26 | // Monster Oron originates from planet Uranus -------------------------------------------------------------------------------- /Chapter11/code/hashsets.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashSet; 2 | 3 | fn main() { 4 | let mut m1: HashSet<&str> = vec!["Cyclops", "Raven", "Gilgamesh"].into_iter().collect(); 5 | let m2: HashSet<&str> = vec!["Moron", "Keshiu", "Raven"].into_iter().collect(); 6 | 7 | m1.insert("Moron"); 8 | if m1.insert("Raven") { 9 | println!("New value added") 10 | } 11 | else { 12 | println!("This value is already present") 13 | } 14 | 15 | println!("m1: {:?}", m1); 16 | 17 | println!("Intersection: {:?}", m1.intersection(&m2).collect::>()); 18 | println!("Union: {:?}", m1.union(&m2).collect::>()); 19 | println!("Difference: {:?}", m1.difference(&m2).collect::>()); 20 | println!("Symmetric Difference: {:?}", 21 | m1.symmetric_difference(&m2).collect::>()); 22 | } 23 | // This value is already present 24 | // m1: {"Moron", "Raven", "Cyclops", "Gilgamesh"} 25 | // Intersection: ["Moron", "Raven"] 26 | // Union: ["Moron", "Gilgamesh", "Raven", "Cyclops", "Keshiu"] 27 | // Difference: ["Gilgamesh", "Cyclops"] 28 | // Symmetric Difference: ["Cyclops", "Gilgamesh", "Keshiu"] 29 | -------------------------------------------------------------------------------- /Chapter11/code/hello.txt: -------------------------------------------------------------------------------- 1 | "Hello Rust World!" 2 | -------------------------------------------------------------------------------- /Chapter11/code/info.txt: -------------------------------------------------------------------------------- 1 | Barak 2 | Vladimir -------------------------------------------------------------------------------- /Chapter11/code/lorem_ipsum.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 2 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 3 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 4 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 5 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 6 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 7 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 8 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 9 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 10 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 11 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 12 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 13 | -------------------------------------------------------------------------------- /Chapter11/code/lorem_ipsum2.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 2 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 3 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 4 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 5 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 6 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 7 | -------------------------------------------------------------------------------- /Chapter11/code/numbers.txt: -------------------------------------------------------------------------------- 1 | 120 345.56 2 | 125 341.56 -------------------------------------------------------------------------------- /Chapter11/code/paths.rs: -------------------------------------------------------------------------------- 1 | // code from Chapter 11/code/paths.rs: 2 | use std::path::Path; 3 | 4 | fn main() { 5 | let path = Path::new("hello.txt"); 6 | let display = path.display(); 7 | 8 | // test whether path exists: 9 | if path.exists() { 10 | println!("{} exists", display); 11 | } 12 | else { 13 | panic!("This path or file does not exist!"); 14 | } 15 | 16 | let file = path.file_name().unwrap(); 17 | let extension = path.extension().unwrap(); 18 | let parent_dir = path.parent().unwrap(); 19 | println!("This is file {:?} with extension {:?} in folder {:?}", file, extension, parent_dir); 20 | 21 | // Check if the path is a file 22 | if path.is_file() { println!("{} is a file", display); } 23 | // Check if the path is a directory 24 | if path.is_dir() { println!("{} is a directory", display); } 25 | 26 | // `join` merges a path with a byte container using the OS specific 27 | // separator, and returns the new path 28 | let new_path = path.join("abc").join("def"); 29 | 30 | // Convert the path into a string slice 31 | match new_path.to_str() { 32 | None => panic!("new path is not a valid UTF-8 sequence"), 33 | Some(s) => println!("new path is {}", s), 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Chapter11/code/read_file.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::fs::File; 3 | use std::io::prelude::*; 4 | use std::error::Error; 5 | 6 | fn main() { 7 | let path = Path::new("hello.txt"); 8 | let display = path.display(); 9 | 10 | // opening a file: 11 | let mut file = match File::open(&path) { 12 | Ok(file) => file, 13 | Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)) 14 | }; 15 | 16 | // reading a file in one chunk: 17 | let mut content = String::new(); 18 | match file.read_to_string(&mut content) { 19 | Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)), 20 | Ok(_) => print!("{} contains:\n{}", display, content), 21 | } 22 | } 23 | // hello.txt contains: 24 | // "Hello Rust World!" -------------------------------------------------------------------------------- /Chapter11/code/read_file_try.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::fs::File; 3 | use std::io::prelude::*; 4 | use std::error::Error; 5 | use std::io; 6 | 7 | fn main() { 8 | let path = Path::new("hello.txt"); 9 | let display = path.display(); 10 | 11 | let content = match read_file(path) { 12 | Err(why) => panic!("error reading {}: {}", display, Error::description(&why)), 13 | Ok(content) => content 14 | }; 15 | 16 | println!("{}", content); 17 | } 18 | 19 | fn read_file(path: &Path) -> Result { 20 | let mut file = try!(File::open(path)); 21 | let mut buf = String::new(); 22 | try!(file.read_to_string(&mut buf)); 23 | Ok(buf) 24 | } 25 | // "Hello Rust World!" 26 | -------------------------------------------------------------------------------- /Chapter11/code/reading_text_file.rs: -------------------------------------------------------------------------------- 1 | use std::io::{BufRead, BufReader}; 2 | use std::fs::File; 3 | 4 | fn main() { 5 | let file = BufReader::new(File::open("numbers.txt").unwrap()); 6 | 7 | // .lines() eats EOF error, so this will only panic if something went completely wrong. 8 | let pairs: Vec<_> = file.lines().map(|line| { 9 | let line = line.unwrap(); 10 | let line = line.trim(); 11 | let mut words = line.split(" "); 12 | let left = words.next().expect("Unexpected empty line!"); 13 | let right = words.next().expect("Expected number!"); 14 | 15 | ( 16 | left.parse::().ok().expect("Expected integer in first column!"), 17 | right.parse::().ok().expect("Expected float in second column!") 18 | ) 19 | }).collect(); 20 | 21 | println!("{:?}", pairs); 22 | } 23 | // [(120, 345.56), (125, 341.56)] 24 | -------------------------------------------------------------------------------- /Chapter11/code/write_file.rs: -------------------------------------------------------------------------------- 1 | static CONTENT: &'static str = 2 | "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 3 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 4 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 5 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 6 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 7 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 8 | "; 9 | 10 | use std::path::Path; 11 | use std::fs::File; 12 | use std::io::prelude::*; 13 | use std::error::Error; 14 | 15 | fn main() { 16 | let path = Path::new("lorem_ipsum.txt"); 17 | let display = path.display(); 18 | 19 | let mut file = match File::create(&path) { 20 | Err(why) => panic!("couldn't create {}: {}", 21 | display, 22 | Error::description(&why)), 23 | Ok(file) => file, 24 | }; 25 | 26 | // variant which does not exit: 27 | // let mut file = match File::create(&path) { 28 | // Err(why) => { println!("couldn't create {}: {}", 29 | // display, 30 | // Error::description(&why)); 31 | // return 32 | // }, 33 | // Ok(file) => file, 34 | // }; 35 | 36 | match file.write_all(CONTENT.as_bytes()) { 37 | Err(why) => { 38 | panic!("couldn't write to {}: {}", 39 | display, 40 | Error::description(&why)) 41 | }, 42 | Ok(_) => println!("successfully wrote to {}", display), 43 | } 44 | 45 | // variant with if-test on successfull write: 46 | if file.write(CONTENT.as_bytes()).is_err() { // error-text not available anymore 47 | println!("Failed to save response."); 48 | return; 49 | } 50 | 51 | 52 | } 53 | // successfully wrote to lorem_ipsum.txt 54 | -------------------------------------------------------------------------------- /Chapter11/code/write_file_try.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::fs::File; 3 | use std::io::prelude::*; 4 | use std::error::Error; 5 | use std::io; 6 | 7 | struct Info { 8 | name: String, 9 | age: i32, 10 | rating: i32 11 | } 12 | 13 | impl Info { 14 | fn as_bytes(&self) -> &[u8] { 15 | self.name.as_bytes() 16 | } 17 | 18 | fn format(&self) -> String { 19 | format!("{};{};{}\n", self.name, self.age, self.rating) 20 | } 21 | } 22 | 23 | fn main() { 24 | let path = Path::new("info.txt"); 25 | let display = path.display(); 26 | 27 | let file = match write_file(&path) { 28 | Err(why) => panic!("couldn't write info to file {}: {}", 29 | display, 30 | Error::description(&why)), 31 | Ok(file) => file, 32 | }; 33 | } 34 | 35 | fn write_file(path: &Path) -> Result { 36 | let mut file = try!(File::create(path)); 37 | let info1 = Info { name:"Donald".to_string(), age: 71, rating: 7 }; 38 | let info2 = Info { name:"Vladimir".to_string(), age: 58, rating: 6 }; 39 | try!(file.write(info1.as_bytes())); 40 | try!(file.write(b"\r\n")); 41 | try!(file.write(info2.as_bytes())); 42 | Ok(file) 43 | } 44 | -------------------------------------------------------------------------------- /Chapter12/code/file_time/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /Chapter12/code/file_time/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "file_time" 3 | version = "0.1.0" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [dependencies] 7 | chrono = "0.4" 8 | -------------------------------------------------------------------------------- /Chapter12/code/file_time/log.txt: -------------------------------------------------------------------------------- 1 | Thu, Aug 17 2017 10:59:33 AM 2 | -------------------------------------------------------------------------------- /Chapter12/code/file_time/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate chrono; 2 | 3 | use chrono::prelude::*; 4 | use std::io::prelude::*; 5 | use std::fs::File; 6 | use std::io; 7 | 8 | fn main() { 9 | let local: DateTime = Local::now(); 10 | let formatted = local.format("%a, %b %d %Y %I:%M:%S %p\n").to_string(); 11 | 12 | match log_info("log.txt", &formatted) { 13 | Ok(_) => println!("Time is written to file!"), 14 | Err(_) => println!("Error: could not create file.") 15 | } 16 | } 17 | 18 | fn log_info(filename: &str, string: &str) -> io::Result<()> { 19 | let mut f = try!(File::create(filename)); 20 | try!(f.write_all(string.as_bytes())); 21 | Ok(()) 22 | } -------------------------------------------------------------------------------- /Chapter12/code/mongodb.rs: -------------------------------------------------------------------------------- 1 | // connecting to mongodb and some commands: 2 | // this code is meant only as an example snippet 3 | // it will not compile 4 | // Direct connection to a server. Will not look for other servers in the topology. 5 | let client = Client::connect("localhost", 27017) 6 | .expect("Failed to initialize client."); 7 | 8 | let coll = client.db("media").collection("movies"); 9 | coll.insert_one(doc!{ "title" => "Back to the Future" }, None).unwrap(); 10 | coll.update_one(doc!{}, doc!{ "director" => "Robert Zemeckis" }, None).unwrap(); 11 | coll.delete_many(doc!{}, None).unwrap(); 12 | 13 | let mut cursor = coll.find(None, None).unwrap(); 14 | for result in cursor { 15 | if let Ok(item) = result { 16 | if let Some(&Bson::String(ref title)) = item.get("title") { 17 | println!("title: {}", title); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter12/code/piston101/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /Chapter12/code/piston101/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "piston101" 3 | version = "0.1.0" 4 | authors = ["Ivo Balbaert "] 5 | 6 | [dependencies] 7 | piston_window = "0.61.0" 8 | -------------------------------------------------------------------------------- /Chapter12/code/piston101/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate piston_window; 2 | 3 | use piston_window::*; 4 | 5 | fn main() { 6 | let mut window: PistonWindow = 7 | WindowSettings::new("Hello Piston!", [640, 480]) 8 | .exit_on_esc(true).build().unwrap(); 9 | while let Some(event) = window.next() { 10 | window.draw_2d(&event, |context, graphics| { 11 | clear([1.0; 4], graphics); 12 | ellipse([0.0, 0.0, 1.0, 0.5], 13 | [0.0, 0.0, 100.0, 100.0], 14 | context.transform, 15 | graphics); 16 | }); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter12/code/web_dev.rs: -------------------------------------------------------------------------------- 1 | // this file does not compile 2 | // it shows only "hello-world" example snippets for the most popular web frameworks. 3 | // iron framework: 4 | extern crate iron; 5 | 6 | use iron::prelude::*; 7 | use iron::status; 8 | 9 | fn main() { 10 | Iron::new(|_: &mut Request| { 11 | Ok(Response::with((status::Ok, "Hello World!"))) 12 | }).http("localhost:3000").unwrap(); 13 | } 14 | 15 | // nickel framework: 16 | #[macro_use] extern crate nickel; 17 | 18 | use nickel::{Nickel, HttpRouter}; 19 | 20 | fn main() { 21 | let mut server = Nickel::new(); 22 | server.get("**", middleware!("Hello World")); 23 | server.listen("127.0.0.1:6767"); 24 | } 25 | 26 | // rocket framework: 27 | #![feature(plugin)] 28 | #![plugin(rocket_codegen)] 29 | 30 | extern crate rocket; 31 | 32 | #[get("/")] 33 | fn index() -> &'static str { 34 | "Hello, world!" 35 | } 36 | 37 | fn main() { 38 | rocket::ignite().mount("/", routes![index]).launch(); 39 | } 40 | 41 | // gotham framework: 42 | extern crate futures; 43 | extern crate hyper; 44 | extern crate gotham; 45 | extern crate mime; 46 | 47 | use hyper::server::Http; 48 | use hyper::{Request, Response, StatusCode}; 49 | 50 | use gotham::http::response::create_response; 51 | use gotham::state::State; 52 | use gotham::handler::NewHandlerService; 53 | 54 | pub fn say_hello(state: State, _req: Request) -> (State, Response) { 55 | let res = create_response( 56 | &state, 57 | StatusCode::Ok, 58 | Some(( 59 | String::from("Hello World!").into_bytes(), 60 | mime::TEXT_PLAIN, 61 | )), 62 | ); 63 | 64 | (state, res) 65 | } 66 | 67 | pub fn main() { 68 | let addr = "127.0.0.1:7878".parse().unwrap(); 69 | 70 | let server = Http::new() 71 | .bind(&addr, NewHandlerService::new(|| Ok(say_hello))) 72 | .unwrap(); 73 | 74 | println!( 75 | "Listening on http://{}", 76 | server.local_addr().unwrap() 77 | ); 78 | 79 | server.run().unwrap(); 80 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------