diff --git a/deps/examples/destructuring.rs b/deps/examples/destructuring.rs new file mode 100644 index 00000000..58fd57d6 --- /dev/null +++ b/deps/examples/destructuring.rs @@ -0,0 +1,15 @@ +fn main() { + // destructuring tuples + let (_x, _y, _z) = (1, 2, 3); + + // destructuring structs + struct Point { + x: i32, + y: i32, + } + + let p = Point { x: 0, y: 7 }; + let Point { x: _a, y: _b } = p; // a = 0, b = 7 + let Point { x, y } = p; // simpler + let _ = (x, y); +} diff --git a/deps/examples/shadowing.rs b/deps/examples/shadowing.rs new file mode 100644 index 00000000..a2ab3be9 --- /dev/null +++ b/deps/examples/shadowing.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 5; // x is immutable + + let x = x + 1; // redefines x + println!("{x}"); + + let x = "example"; // the type can change + println!("{x}"); +} diff --git a/deps/examples/vars_and_consts.rs b/deps/examples/vars_and_consts.rs new file mode 100644 index 00000000..bd63c5ec --- /dev/null +++ b/deps/examples/vars_and_consts.rs @@ -0,0 +1,9 @@ +#![allow(unused)] +fn main() { + // `const` is set to a constant expression; the type must be annotated + const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; + + let apples = 5; // immutable variable + + let mut guess = String::new(); // mutable variable +} diff --git a/src/lang/variables_and_constants.md b/src/lang/variables_and_constants.md index 770e8a7e..31e53ebd 100644 --- a/src/lang/variables_and_constants.md +++ b/src/lang/variables_and_constants.md @@ -1,36 +1,19 @@ # Variables and Constants ```rust,editable -fn main() { - const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; // set only to a constant expression; type must be annotated - let apples = 5; // immutable - let mut guess = String::new(); // mutable -} +{{#include ../../deps/examples/vars_and_consts.rs}} ``` ## Shadowing ```rust,editable -fn main() { - let x = 5; - let x = x + 1; // redefines x; type can change -} +{{#include ../../deps/examples/shadowing.rs}} ``` ## Destructuring ```rust,editable -fn main() { - // destructuring tuples - let (x, y, z) = (1, 2, 3); - - // destructuring structs - struct Point{ x: i32, y: i32, } - - let p = Point { x: 0, y: 7 }; - let Point { x: a, y: b } = p; // a = 0, b = 7 - let Point { x, y } = p; // simpler -} +{{#include ../../deps/examples/destructuring.rs}} ``` Starting the name of a variable with an underscore silences unused variable warnings.