update variable.md

This commit is contained in:
sunface 2022-02-28 16:57:04 +08:00
parent ffaa2116f5
commit cb15ef484b
1 changed files with 17 additions and 14 deletions

View File

@ -25,9 +25,10 @@ fn main() {
``` ```
### Scope ### Scope
🌟 A scope is the range within the program for which the item is valid. A scope is the range within the program for which the item is valid.
```rust,editable ```rust,editable.
🌟
// fix the error below with least modifying // fix the error below with least modifying
fn main() { fn main() {
let x: i32 = 10; let x: i32 = 10;
@ -53,8 +54,9 @@ fn define_x() {
``` ```
### Shadowing ### Shadowing
🌟🌟 You can declare a new variable with the same name as a previous variable, here we can say **the first one is shadowed by the second one. You can declare a new variable with the same name as a previous variable, here we can say **the first one is shadowed by the second one.
🌟🌟
```rust,editable ```rust,editable
// only modify `assert_eq!` to make the `println!` work(print `42` in terminal) // only modify `assert_eq!` to make the `println!` work(print `42` in terminal)
@ -72,9 +74,10 @@ fn main() {
} }
``` ```
🌟🌟 remove a line in code to make it compile 🌟🌟
```rust,editable ```rust,editable
// remove a line in code to make it compile
fn main() { fn main() {
let mut x: i32 = 1; let mut x: i32 = 1;
x = 7; x = 7;
@ -106,13 +109,14 @@ fn main() {
// warning: unused variable: `x` // warning: unused variable: `x`
``` ```
### Destructing ### Destructuring
🌟🌟 fix the error below with least modifying 🌟🌟 We can use a pattern with `let` to destructure a tuple to separate variables.
> Tips: you can use Shadowing or Mutability > Tips: you can use Shadowing or Mutability
```rust,editable ```rust,editable
// fix the error below with least modifying
fn main() { fn main() {
let (x, y) = (1, 2); let (x, y) = (1, 2);
x += 2; x += 2;
@ -123,20 +127,19 @@ fn main() {
``` ```
### Destructuring assignments ### Destructuring assignments
🌟🌟 fix the code with two ways: Introducing in Rust 1.59: You can now use tuple, slice, and struct patterns as the left-hand side of an assignment.
- Shadowing with adding `let`
- make types compatible
🌟
> Note: the feature `Destructuring assignments` need 1.59 or higher Rust version > Note: the feature `Destructuring assignments` need 1.59 or higher Rust version
```rust,editable ```rust,editable
fn main() { fn main() {
let (mut x, mut y) = (1.0, 2.0); let (x, y);
(x,y) = (3, 4); (x,..) = (3, 4);
[.., y] = [1, 2];
assert_eq!([x,y],[3, 4]); // fill the blank to make the code work
assert_eq!([x,y], __);
} }
``` ```