Skip to content

Commit 1381425

Browse files
authored
Merge pull request #4 from tainguyenbp/feat/learn-programming-rust-lang03
test pointer and closures
2 parents 35d5a9b + 70649bd commit 1381425

14 files changed

+56
-0
lines changed
412 KB
Binary file not shown.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
let x = 4;
3+
println!("{}", get_square_value(x));
4+
}
5+
6+
fn get_square_value(i: i32) -> i32 {
7+
i * i
8+
}
412 KB
Binary file not shown.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
fn main() {
2+
let x = 65536;
3+
let square = |i: i32| -> i32 { // Input parameters are passed inside | | and expression body is wrapped within { }
4+
i * i
5+
};
6+
println!("{}", square(x));
7+
}
412 KB
Binary file not shown.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fn main() {
2+
let x = 40;
3+
let square = |i| i * i; // { } are optional for single-lined closures
4+
println!("{}", square(x));
5+
}
412 KB
Binary file not shown.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fn main() {
2+
let x = 300;
3+
let x_square = |i: i32| -> i32 { i * i }(x); // { } are mandatory while creating and calling same time.
4+
println!("{}", x_square);
5+
}
412 KB
Binary file not shown.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fn main() {
2+
let x = 68;
3+
let x_square = |i| -> i32 { i * i }(x); // ⭐️ The return type is mandatory.
4+
println!("{}", x_square);
5+
}
Binary file not shown.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
3+
fn main() {
4+
// 01. Without type declarations.
5+
let p1 = plus_one;
6+
let x = p1(9); // 6
7+
8+
println!("Result: {}", x);
9+
10+
}
11+
12+
13+
fn plus_one(a: i32) -> i32 {
14+
a + 1
15+
}
Binary file not shown.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fn main() {
2+
// 02. With type declarations.
3+
let p1: fn(i32) -> i32 = plus_one;
4+
let x = p1(7);
5+
6+
println!("Result: {}", x);
7+
}
8+
9+
fn plus_one(a: i32) -> i32 {
10+
a + 1
11+
}

0 commit comments

Comments
 (0)