2022-02-23 00:49:02 -06:00
|
|
|
# Statements and Expressions
|
2022-02-25 00:24:23 -06:00
|
|
|
|
|
|
|
### Examples
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
let x = 5u32;
|
|
|
|
|
|
|
|
let y = {
|
|
|
|
let x_squared = x * x;
|
|
|
|
let x_cube = x_squared * x;
|
|
|
|
|
|
|
|
// This expression will be assigned to `y`
|
|
|
|
x_cube + x_squared + x
|
|
|
|
};
|
|
|
|
|
|
|
|
let z = {
|
|
|
|
// The semicolon suppresses this expression and `()` is assigned to `z`
|
|
|
|
2 * x;
|
|
|
|
};
|
|
|
|
|
|
|
|
println!("x is {:?}", x);
|
|
|
|
println!("y is {:?}", y);
|
|
|
|
println!("z is {:?}", z);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### Exercises
|
2022-03-02 02:27:16 -06:00
|
|
|
1. ππ
|
2022-02-25 00:24:23 -06:00
|
|
|
```rust,editable
|
2022-03-02 02:27:16 -06:00
|
|
|
// make it work with two ways
|
2022-02-25 00:24:23 -06:00
|
|
|
fn main() {
|
|
|
|
let v = {
|
|
|
|
let mut x = 1;
|
|
|
|
x += 2
|
|
|
|
};
|
|
|
|
|
|
|
|
assert_eq!(v, 3);
|
2022-03-05 00:48:43 -06:00
|
|
|
|
|
|
|
println!("Success!")
|
2022-02-25 00:24:23 -06:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2022-03-02 02:27:16 -06:00
|
|
|
2. π
|
2022-02-25 00:24:23 -06:00
|
|
|
```rust,editable
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let v = (let x = 3);
|
|
|
|
|
|
|
|
assert!(v == 3);
|
2022-03-05 00:48:43 -06:00
|
|
|
|
|
|
|
println!("Success!")
|
2022-02-25 00:24:23 -06:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2022-03-02 02:27:16 -06:00
|
|
|
3. π
|
2022-02-25 00:24:23 -06:00
|
|
|
```rust,editable
|
|
|
|
|
2022-03-02 02:27:16 -06:00
|
|
|
fn main() {
|
|
|
|
let s = sum(1 , 2);
|
|
|
|
assert_eq!(s, 3);
|
2022-03-05 00:48:43 -06:00
|
|
|
|
|
|
|
println!("Success!")
|
2022-03-02 02:27:16 -06:00
|
|
|
}
|
2022-02-25 00:24:23 -06:00
|
|
|
|
|
|
|
fn sum(x: i32, y: i32) -> i32 {
|
|
|
|
x + y;
|
|
|
|
}
|
2022-03-01 08:06:38 -06:00
|
|
|
```
|
|
|
|
|
|
|
|
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|