<style>
.reveal {
font-size: 26px;
}
</style>
# Rust
or: how I stopped worrying about multi threading

<!-- Put the link to this slide here so people can follow -->
slide: https://hackmd.io/p/template-Talk-slide
---
# Qualifikationen
Was qualifiziert mich über das Thema zu reden?

* Viel mit C auf die Nase gefallen
* Habe es nie über 10 Zeilen C geschafft ohne Memory-Leak
* Zuhause in der Python Welt
* Ein Fan geworden von statischer Codeanalyse
---
# Das Quadrad der Typisierung
| | Statisch | Dynamisch |
| -------- | -------- | --------- |
| Streng | Rust, Java, Kotlin | Python |
| Schwach | C, C++ | PHP, JS |
----
## Schwach + Dynamisch
```php=
function add($a, $b) {
return $a + $b;
}
$res = add("11", 2);
echo "$res\n";
// -> 13
```
----
## Streng + Dynamisch
Typen werden zur Laufzeit bestimmt
```python=
fn add(a, b):
return a + b
add("11", 2)
# -> TypeError: can only concatenate str (not "int") to str
```
---
# Sprachfeatures
* imperativ
* functional
* pattern matching
* object orientiert
* weitgehend ohne Vererbungsmodell
* OO durch modellierung von Nachrichtensystemen (`trait`)
* kein Garbage Collector
----
# Sprachfeatures
* imperativ
* functional
* pattern matching
* object orientiert
* weitgehend ohne Vererbungsmodell
* OO durch modellierung von Nachrichtensystemen (`trait`)
* kein Garbage Collector **und** meist keine Speicherverwaltung
----
## Object oriented programming
> I'm sorry that I, long ago, coined the term "Objects" for
> this topic, because it gets many people to focus on the
> lesser idea.
>
> The big idea is messaging!
*Alan Kay Object Orientation (1966)*
Source: [Continous Delivery: OOP vs Functional](https://www.youtube.com/watch?v=wyABTfR9UTU)
----
## Pattern matching
```rust=
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
```
*Quelle*: [Rust Book](https://doc.rust-lang.org/book/ch06-02-match.html)
----
## Pattern matching
```rust=
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
}
}
}
fn main() {
let c = Coin::Penny;
println!("{}", value_in_cents(c));
let c = Coin::Quarter(UsState::Alabama);
println!("{}", value_in_cents(c));
}
```
*Quelle*: [Rust Book](https://doc.rust-lang.org/book/ch06-02-match.html)
<!--
Matching ist vergleichbar mit Query by Example
-->
----
## Zero Cost Abstraction
* Compiler prüft strenge Vorgaben
* Compiler entfernt
```
enum Animal {
Dog,
Cat,
}
fn call(animal: Animal) {
match animal {
Animal::Dog => println!("wau"),
Animal::Cat => println!("miau"),
};
}
```
----
## Kein NULL/nil/None Value
[the worst mistake of computer science](https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/)
None variant statt None Type:
```rust=
fn myprint(val: Option<u64>) {
match val {
Some(i) => println!("Value: {}", i),
None => println!("Value not set")
};
}
fn main() {
myprint(Some(12)); // -> Value: 12
myprint(None); // -> Value not set
}
```
----
## Fehlerbehandlung
`Result` statt Exceptions.
```rust=
#[derive(Debug)]
enum Error {
Overflow,
}
fn add(a: u8, b: u8) -> Result<u8, Error> {
match a.checked_add(b) {
Some(c) => Ok(c),
None => Err(Error::Overflow),
}
}
fn main() -> Result<(), Error> {
let sum = add(44, 23)?;
println!("Got {}", sum); // Got 67
let sum = add(200, 200)?; // Error: Overflow + exit(1)
println!("Got {}", sum);
Ok(())
}
```
---
## Was is nun mit dem multi threading

---
### Speicherverwaltung
Wo liegen meine Daten? Das hängt davon ab, wann die Größe bekannt ist.
* Zur Kompilierzeit -> Programm stack
* Zur Laufzeit -> im Programm heap
<img src="https://i.imgur.com/mjKb5VM.png" height=350></img>
*Quelle* [O'Reilly](https://www.oreilly.com/library/view/rust-essentials/9781788390019/0b621954-95fa-4b2a-b4de-7ced61027a3e.xhtml)
----
### Speicherverwaltung in C
```c=
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char *greeting;
greeting = (char *) malloc(15); // Speicher im Heap
strcpy(greeting, "Hello");
printf("%s World\n", greeting);
free(greeting);
return 0;
}
```
----
### Speicherverwaltung in Rust (Ownership)
```rust=
fn main() {
let greeting = String::from("Hello");
println!("{} World", greeting);
} // free here
```
----
### Speicherverwaltung in Rust (Ownership)
```rust=
fn greeting() -> String {
return String::from("Hello")
}
fn speak(greeting: String) {
println!("{} World", greeting);
} // free here
fn main() {
let txt = greeting();
speak(txt);
}
```
----
### Speicherverwaltung in Rust (Borrowing)
```rust=
fn greeting() -> String {
return String::from("Hello")
}
fn speak(greeting: String) {
println!("{} World", greeting);
}
fn main() {
let txt = greeting();
speak(txt);
speak(txt);
}
```
:x:

----
### Speicherverwaltung in Rust (Borrowing)
```rust=
fn greeting() -> String {
return String::from("Hello")
}
fn speak(greeting: &String) {
println!("{} World", greeting);
}
fn main() {
let txt = greeting();
speak(txt);
speak(txt);
} // free here
```
:heavy_check_mark:
---
## Multithreading?

---
## Thread safety probleme
Semaphoren sind hart umzusetzen und durchzusetzten
Rust bietet dafür im Thema data-races
* Ownership model (thread-safety + memory-safety)
* Threadsafe Reference Counted Container
* Mutex
* MPSC Kanäle (multi producer, single consumer)
---
# Ökosystem
+ `rustc`
+ LLVM compiler
+ GCC backend unstable
+ `rustup` pflegt
+ verschiedene rust versionen
+ cross compliation
+ cargo
+ packet manager
+ erweiterbares plugin system
+ [rust-analzer](https://github.com/rust-analyzer/rust-analyzer)
+ language server für editor integration
+ clippy
+ Code smell
+ rustfmt
+ Formatierung von Rust
---
# Sichtbare complexität
<img src="https://i.imgur.com/86KQ5bf.png" height=450></img>
[Quelle](https://twitter.com/timClicks/status/1450943515635056648?t=qJ9SGtEn3dtiXnGtn-AQrg&s=09)
<!-- OSString vs String bei Dateisystemen -->
---
# Wer setzt es bereits ein
* Mozilla / Firefox
* Microsoft: [Microsoft Security Response Center](https://msrc-blog.microsoft.com/2020/04/29/the-safety-boat-kubernetes-and-rust/), [ZDNet Article](https://www.zdnet.com/article/microsoft-why-we-used-programming-language-rust-over-go-for-webassembly-on-kubernetes-app/)
* Discord: [Blog Go -> Rust](https://blog.discord.com/why-discord-is-switching-from-go-to-rust-a190bbca2b1f), [On scale](https://blog.discord.com/using-rust-to-scale-elixir-for-11-million-concurrent-users-c6f19fc029d3)
* AWS: [Bottlerocket: Rust Linux Container](https://www.zdnet.com/article/aws-introduces-bottlerocket-a-rust-language-oriented-linux-for-containers/)
{"metaMigratedAt":"2023-06-16T18:45:49.750Z","metaMigratedFrom":"YAML","title":"Rust or: how I stopped worrying about multi threading","breaks":true,"description":"Introduction into Rust and Ecosystem","contributors":"[{\"id\":\"bb7dc7c9-31fd-4a5c-a52d-d96ddf9fa911\",\"add\":8759,\"del\":1010}]"}