From 6d6e600720e7027e713e466892df8e4ecf653863 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 6 Oct 2021 19:40:31 -0400 Subject: [PATCH] RBE more variable bindings fun --- rustbyexample/variable_bindings/declare.rs | 19 +++++++++++++++++++ rustbyexample/variable_bindings/freeze.rs | 11 +++++++++++ rustbyexample/variable_bindings/scope.rs | 12 ++++++++++++ rustbyexample/variable_bindings/scope2.rs | 16 ++++++++++++++++ 4 files changed, 58 insertions(+) create mode 100644 rustbyexample/variable_bindings/declare.rs create mode 100644 rustbyexample/variable_bindings/freeze.rs create mode 100644 rustbyexample/variable_bindings/scope.rs create mode 100644 rustbyexample/variable_bindings/scope2.rs diff --git a/rustbyexample/variable_bindings/declare.rs b/rustbyexample/variable_bindings/declare.rs new file mode 100644 index 0000000..b51f3db --- /dev/null +++ b/rustbyexample/variable_bindings/declare.rs @@ -0,0 +1,19 @@ +fn main() { + let a_binding; + + { + let x = 2; + + a_binding = x * x; + } + + println!("a binding: {}", a_binding); + + let another_binding; + + //println!("another binding: {}", another_binding); + + another_binding = 1; + + println!("another binding: {}", another_binding); +} diff --git a/rustbyexample/variable_bindings/freeze.rs b/rustbyexample/variable_bindings/freeze.rs new file mode 100644 index 0000000..1e9791c --- /dev/null +++ b/rustbyexample/variable_bindings/freeze.rs @@ -0,0 +1,11 @@ +fn main() { + let mut _mutable_integer = 7i32; + + { + let _mutable_integer = _mutable_integer; + + // _mutable_integer = 50; + } + + _mutable_integer = 3; +} diff --git a/rustbyexample/variable_bindings/scope.rs b/rustbyexample/variable_bindings/scope.rs new file mode 100644 index 0000000..d7d4d1d --- /dev/null +++ b/rustbyexample/variable_bindings/scope.rs @@ -0,0 +1,12 @@ +fn main() { + let long_lived_binding = 1; + + { + let short_lived_binding = 2; + println!("inner short: {}", short_lived_binding); + } + + // println!("outer short: {}", short_lived_binding); + + println!("outer long: {}", long_lived_binding); +} diff --git a/rustbyexample/variable_bindings/scope2.rs b/rustbyexample/variable_bindings/scope2.rs new file mode 100644 index 0000000..b0cc34d --- /dev/null +++ b/rustbyexample/variable_bindings/scope2.rs @@ -0,0 +1,16 @@ +fn main() { + let shadowed_binding = 1; + + { + println!("before being shadowed: {}", shadowed_binding); + + let shadowed_binding = "abc"; + + println!("shadowed in inner block: {}", shadowed_binding); + } + println!("outside inner block: {}", shadowed_binding); + + let shadowed_binding = 2; + println!("shadowed in outer block: {}", shadowed_binding); +} +