rust-by-practice/solutions/variables.md

144 lines
1.7 KiB
Markdown
Raw Permalink Normal View History

2022-05-01 00:08:50 -05:00
1.
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let x: i32 = 5; // uninitialized but using, ERROR !
let y: i32; // uninitialized but also unusing, only warning
2022-05-01 00:08:50 -05:00
println!("{} is equal to 5", x);
2022-03-01 07:56:43 -06:00
}
```
2.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
2022-05-01 00:08:50 -05:00
let mut x = 1;
x += 2;
println!("{} is equal to 3", x);
2022-03-01 07:56:43 -06:00
}
```
3.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let x: i32 = 10;
2022-10-11 03:42:36 -05:00
let y: i32 = 20;
2022-03-01 07:56:43 -06:00
{
let y: i32 = 5;
println!("The value of x is {} and value of y is {}", x, y);
}
2022-10-11 03:42:36 -05:00
println!("The value of x is {} and value of y is {}", x, y);
2022-03-01 07:56:43 -06:00
}
```
4.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let x = define_x();
2022-05-01 00:08:50 -05:00
println!("{}, world", x);
2022-03-01 07:56:43 -06:00
}
fn define_x() -> String {
let x = "hello".to_string();
x
}
```
2022-04-13 00:34:14 -05:00
```rust
fn main() {
let x = define_x();
2022-05-01 00:08:50 -05:00
println!("{:?}, world", x);
2022-04-13 00:34:14 -05:00
}
fn define_x() -> &'static str {
let x = "hello";
x
}
```
2022-03-01 07:56:43 -06:00
5.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let x: i32 = 5;
{
let x = 12;
assert_eq!(x, 12);
}
assert_eq!(x, 5);
2022-05-01 00:08:50 -05:00
let x = 42;
2022-03-01 07:56:43 -06:00
println!("{}", x); // Prints "42".
}
```
6.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let mut x: i32 = 1;
x = 7;
2022-10-11 03:56:18 -05:00
// Shadowing and re-binding
let x = x;
2022-03-01 07:56:43 -06:00
let y = 4;
2022-10-11 03:56:18 -05:00
// Shadowing
let y = "I can also be bound to text!";
println!("Success!");
2022-03-01 07:56:43 -06:00
}
```
7.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
2022-05-01 00:08:50 -05:00
let _x = 1;
2022-03-01 07:56:43 -06:00
}
```
```rust
#[allow(unused_variables)]
fn main() {
2022-05-01 00:08:50 -05:00
let x = 1;
2022-03-01 07:56:43 -06:00
}
```
8.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let (mut x, y) = (1, 2);
x += 2;
assert_eq!(x, 3);
assert_eq!(y, 2);
}
```
```rust
fn main() {
let (x, y) = (1, 2);
let x = 3;
assert_eq!(x, 3);
assert_eq!(y, 2);
}
```
9.
2022-05-01 00:08:50 -05:00
2022-03-01 07:56:43 -06:00
```rust
fn main() {
let (x, y);
2022-05-01 00:08:50 -05:00
(x, ..) = (3, 4);
2022-03-01 07:56:43 -06:00
[.., y] = [1, 2];
// fill the blank to make the code work
2022-05-01 00:08:50 -05:00
assert_eq!([x, y], [3, 2]);
2022-03-01 07:56:43 -06:00
}
```