Professional Documents
Culture Documents
## Basics
---
```rust
fn main() {
println!("Hello, world!");
}
```
### · Strings
```rust
fn main() {
let mut text = String::new();
}
```
```rust
fn main() {
let number = 10;
let guess = 5;
match guess.cmp(&number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("Eureka!")
}
}
```
### · Shadowing
```rust
let spaces: String = " ";
let spaces: usize = spaces.len(); // 'usize' is the size of a pointer.
```
## Data Types
---
```rust
let x = 2.0; // f64
let y: f32 = 3.0; // f32
```
```rust
let t = true;
let f: bool = false;
```
```rust
let c = 'z';
let z: char = 'Z';
let heart_eyed_cat = '😻';
```
#### · Tuple
```rust
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // destructuring
let first = tup.0; // access element
```
#### · Array
```rust
let a = [1, 2, 3, 4, 5];
let b: [f32; 3] = [1.3, 65.9, 8.6];
let c = [3; 5]; // c = [3, 3, 3, 3, 3, 3]
let first = a[0];
```
```rust
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
```
```rust
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32)
}
impl Message {
fn call(&self) {
// ...
}
}
```
```rust
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
```
```rust
let value = 0u8; // u8 number
match value {
1 => println!("one"),
3 => println!("three"),
5 => println!("five"),
7 => println!("seven"),
_ => (), // placeholder
}
```
## Collections
---
### Vector
```rust
let v: Vec<i32> = Vec::new();
let u = vec![1, 2, 3]; // vec! macro
v.push(5);
v.push(7);
```