rust : wip.

This commit is contained in:
Dmitry Voronin 2023-11-19 00:23:43 +03:00
parent b7d02f7a3b
commit 7e1e703b8e
3 changed files with 129 additions and 0 deletions

31
dev/lang/rust/enum.md Normal file
View file

@ -0,0 +1,31 @@
# Emun.
# Create.
```rust
enum Message {
Quit,
Echo(String),
Move { x: i32, y: i32 },
ChangeColor(i32, i32, i32)
}
impl Message {
fn call(&self) {
println!("{:?}", self);
}
}
fn main() {
let messages = [
Message::Move { x: 10, y: 30 },
Message::Echo(String::from("hello world")),
Message::ChangeColor(128, 16, 32),
Message::Quit
];
for message in &messages {
message.call();
}
}
```

88
dev/lang/rust/struct.md Normal file
View file

@ -0,0 +1,88 @@
# Struct.
# Types.
## Classic.
```rust
struct ColorClassicStruct {
red: i32,
green: i32,
blue: i32,
}
```
```rust
let mut green = ColorClassicStruct {
red: 0,
green: 255,
blue: 0,
}
green.red = green.blue;
```
## Tuple.
Have no field names.
```rust
struct Point(i32, i32, i32);
let x = Point(0, 0, 0);
```
## Unit-like.
Have nothing. TODO: add use-cases.
```rust
struct AlwaysEqual;
let subject = AlwaysEqual;
```
# Shortcuts.
## Field-init.
Copy values with the same name.
```rust
fn create_color(red: i32, green: i32, blue: i32) -> ColorClassicStruct {
ColorClassicStruct {
red,
green,
blue,
}
}
```
## Struct update.
Copy the rest of the struct.
```rust
let color2 = ColorClassicStruct {
red: 255,
..color1
};
```
# Logic.
You can write logic in structs.
```rust
struct Package {
sender_country: String,
recipient_country: String,
fee: u32
}
impl Package {
fn is_international(&self) -> bool {
self.sender_country != self.recipient_country
}
}
```

View file

@ -23,3 +23,13 @@ for (item in vector.iter_mut()) {} // Mutable iterate.
```rust
vector.iter().map(|element| {}).collect()
```
# Copy.
## Clone.
You can clone a Vec in cases when you need to modify a copy.
```rust
foo(vector.clone())
```