1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
# Scalar
[[Integers can overflow if compiled with --release]]
[[Char is a unicode scalar value]]
`bool`
`char`
integer (signed, unsigned): `i/u8`, `i/u16`,` i/u32`, `i/u64`, `i/u128` or `i/usize` (cpu arch).
`f32` or `f64`
#### Number Literals
Decimal: `500_000_000`
Hex: `0xff`
Octal: `0o77`
Binary: `0b1111_0000`
Byte (u8 only): `b'A'`
# Compound
tuple: `(i32, f64, char)`
array: `[i32; len]`
[[Accessing a tuple by index is different from an array]]
[[An empty tuple is called a unit]]
[[Primitive values such as the array are allocated on the stack]]
[[Arrays are useful when you know the length will not change]]
[[Array notation]]
string slice: `&str`
general slice: `&[type]` ie `&[i32]` or `&[String]` which is different from `&str`.
[[Difference between string slice and slice of strings]]
## Structs
[[Rust struct init shorthand]]
[[Rust struct update syntax]]
[[Rust struct associated functions]]
```rust
struct Blaat {
name: i32,
other: String,
}
```
**tuple struct**
Type enforcement so we know what we're dealing with is semantically correct.
```rust
struct Point3D(i32, i32, i32);
```
**unit struct**
useful for implementing behaviour that doesn't require data.
```rust
struct Blaat;
```
## Enums
[[The option enum]]
```rust
enum IpAddrKind {
V4(i8, i8, i8, i8)
V6(String)
}
IpAddrKind::V4(String::from(127, 0, 0, 1));
```
It is obviously also possible to use custom type's (ie struct) in an enum so the above could be rewritten as
```rust
struct IPV4Addr { ... }
struct IPV6Addr { ... }
enum IPAddr {
V4(IPV4Addr)
V6(IPV6Addr)
}
```
In this sense enum's can be used as some sort of inheritance, ie both are IPAddr's.
It is also possible to associate functions with enum's using `impl`.
#### Match
```rust
match {
IpAddr::V4(s1, s2, s3, s4) => {
println!("ip address = {}.{}.{}.{}", s1, s2, s3, s4);
}
other => something(),
_ => (),
}
```
##### using if let or else let matching
```rust
fn handle_message(msg: Msg) {
if let Message::OK(innerMsg) = msg {
println!("{}", innerMsg)
}
let innerMsg = if let Message::OK(innerMsg) = msg {
innerMsg
} else {
return None
}
// ^ Can be written as v:
let Message::OK(innerMsg) = msg else {
return None
}
}
```
|