Skip to content

Commit

Permalink
Move variables / const examples to separate .rs files
Browse files Browse the repository at this point in the history
  • Loading branch information
john-cd committed Dec 29, 2023
1 parent 77059fc commit 78c4035
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 20 deletions.
15 changes: 15 additions & 0 deletions deps/examples/destructuring.rs
Original file line number Diff line number Diff line change
@@ -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);
}
9 changes: 9 additions & 0 deletions deps/examples/shadowing.rs
Original file line number Diff line number Diff line change
@@ -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}");
}
9 changes: 9 additions & 0 deletions deps/examples/vars_and_consts.rs
Original file line number Diff line number Diff line change
@@ -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
}
23 changes: 3 additions & 20 deletions src/lang/variables_and_constants.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 78c4035

Please sign in to comment.