rust : wip.

This commit is contained in:
Dmitry Voronin 2023-11-18 09:54:14 +03:00
parent 295198f75d
commit b7d02f7a3b
7 changed files with 179 additions and 0 deletions

32
dev/lang/rust/array.md Normal file
View file

@ -0,0 +1,32 @@
# Arrays.
# Create an array.
Specify the type first, then the count.
```rust
let array: [i32; 5] = [1, 2, 3, 4, 5]; // Manual init.
let array: [i32; 5] = [0; 5]; // All to zeroes.
```
# Get the array size.
Use `.len()` method.
```rust
let size = array.len();
```
# Create a slice.
## Whole array.
```rust
let slice = &array;
```
## Partial.
```rust
let slice = &array[1..4]; // Slice of: 1, 2, 3.
```

37
dev/lang/rust/borrow.md Normal file
View file

@ -0,0 +1,37 @@
# Memory borrowing.
# Reference.
To pass an immutable reference, use `&` sign.
```rust
let s1 = String::from("hello");
foo(&s1);
```
# Mutable reference.
Use `&mut` to pass mutable reference. You can have only one mutable reference at a time.
```rust
let s1 = String::from("world");
foo(&mut s1)
```
# Ownership.
You pass ownership by default: no special syntax.
```rust
let s1 = String::from("hi");
foo(s1) // foo() now owns s1 and s1 is no longer accesible after this call.
```
```rust
fn foo() -> String
{
let s1 = String::from("wow");
return s1;
}
```

View file

@ -5,7 +5,33 @@
Declare functions using `fn` keyword.
```rust
// Simple function.
fn main() {}
// With argument of type i32.
fn main(x: i32) {}
// With return type of i32.
fn main() -> i32 {}
```
# Return value.
## Return keyword.
You can return value by writing `return` keyword. Use this in multiline functions.
```rust
fn foo() -> i32
{
return 10;
}
```
## Last expression.
It is also possible to return the result of the last line by removing `;` at the end. Use this for single-line functions.
```rust
fn foo() -> i32 { 10 }
```

24
dev/lang/rust/if.md Normal file
View file

@ -0,0 +1,24 @@
# If statement.
# Simple switch
```rust
if (x == 10)
{ }
else
{ }
```
# As an expression.
```rust
fn foo(a: i32, b: i32) -> i32 { if (a > b) { a } else { b } }
```
# Variants.
Using `()` is optional, however, `{}` are required.
```rust
if a > b { a } else { b }
```

View file

@ -0,0 +1,15 @@
# Primitive types.
# Boolean.
```rust
let foo: bool = true;
```
# Char.
Char is identified by using single quotes `'c'`.
```rust
let foo: char = 'c';
```

20
dev/lang/rust/tuple.md Normal file
View file

@ -0,0 +1,20 @@
# Tuple.
# Create.
```rust
let cat = ("Fluff", 3.5);
```
# Destructure.
```rust
let (name, age) = cat;
```
# Indexed access.
```rust
let numbers = (1, 2, 3);
let two = numbers.1;
```

25
dev/lang/rust/vector.md Normal file
View file

@ -0,0 +1,25 @@
# Vector.
# Create.
## Using macro.
```rust
let array: [i32; 4] = [10, 20, 30, 40];
let vector: Vec<i32> = vec!(10, 20, 30, 40);
```
# Iterate.
## For-each.
```rust
for (item in vector.iter()) {} // Immutable iterate.
for (item in vector.iter_mut()) {} // Mutable iterate.
```
## Map.
```rust
vector.iter().map(|element| {}).collect()
```