summaryrefslogtreecommitdiff
path: root/Rust Data Types.md
diff options
context:
space:
mode:
Diffstat (limited to 'Rust Data Types.md')
-rw-r--r--Rust Data Types.md113
1 files changed, 113 insertions, 0 deletions
diff --git a/Rust Data Types.md b/Rust Data Types.md
new file mode 100644
index 0000000..d46b2a3
--- /dev/null
+++ b/Rust Data Types.md
@@ -0,0 +1,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
+ }
+}
+``` \ No newline at end of file