summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoruser@node5.net <user@node5.net>2026-07-28 15:38:32 +0200
committeruser@node5.net <user@node5.net>2026-07-28 15:38:32 +0200
commitea9fc9619fccc6f6df9bfd549e73be16d9550477 (patch)
treec3341b4a37a593fd945fe261204a9527f822d069
parent81595f425555450452128801fd3bf7776cfb1ba2 (diff)
Learning rust - Chapter 3 doneHEADmaster
-rw-r--r--misc/Learning rust/index.md320
1 files changed, 317 insertions, 3 deletions
diff --git a/misc/Learning rust/index.md b/misc/Learning rust/index.md
index dd8b064..9449208 100644
--- a/misc/Learning rust/index.md
+++ b/misc/Learning rust/index.md
@@ -3,6 +3,8 @@ description: Notes to self about learning rust
created: 2026-07-22
---
+[TOC]
+
The take aways from [__The__ book on rust](https://doc.rust-lang.org/stable/book/) that took my knowledge from point A to B as primarily a Python developer.
## Chapter 2
@@ -123,7 +125,10 @@ fn main() {
Finally writing some rust i must admit that i find rusts compiler errors are really friendly,
the syntax is plesent and legible, and leads you to handle errors.
-### Temperature converter
+
+### Assignments
+
+#### Temperature converter
```rust
use std::io;
@@ -180,7 +185,7 @@ Your code is solid Rust and it mostly avoids common beginner pitfalls from the b
It validates me, wow, what a supprise ![feel_the_validation.webp](feel_the_validation.webp)
-
+```
1. split_at(input.len() - 2) is brittle and can be incorrect because you compute the index from the untrimmed string length (so whitespace/newline can break the split).
2. Slicing by byte index is unsafe for general cases; indexing must land on a valid char boundary (your current approach assumes a fixed layout).
3. Parsing by “last 2 characters” assumes the unit is always exactly one character and located at a fixed position; inputs like 22 C, missing unit, etc., will fail or behave unexpectedly.
@@ -188,8 +193,317 @@ It validates me, wow, what a supprise ![feel_the_validation.webp](feel_the_valid
5. Using panic!/expect for invalid user input is fine for an exercise, but for real programs you’d prefer returning Result and printing a friendly error.
If you want a robust fix: parse from let trimmed = input.trim(); and take the last non-whitespace character as the unit, then parse the remaining prefix as the number.
+```
+
+Nothing major, but let's address it to learn.
+
+<pre>
+<span style="font-weight:bold;">diff --git a/src/main.rs b/src/main.rs</span>
+<span style="font-weight:bold;">index 9fee6af..2771e71 100644</span>
+<span style="font-weight:bold;">--- a/src/main.rs</span>
+<span style="font-weight:bold;">+++ b/src/main.rs</span>
+<span style="color:teal;">@@ -15,23 +15,17 @@</span> fn main() {
+ io::stdin()
+ .read_line(&amp;mut input)
+ .expect(&quot;Failed to read line&quot;);
+<span style="color:lime;">+</span><span style="color:lime;"> input = input.trim().to_string();</span>
+
+<span style="color:red;">- let (temp, unit) = input.trim().split_at(input.len() - 2);</span>
+<span style="color:lime;">+</span><span style="color:lime;"> let (temp, unit) = input.split_at(input.len() - 1);</span>
+ let unit = unit.to_uppercase();
+
+ let temp: f64 = temp.parse().expect(&amp;format!(&quot;Couldn't parse number from: {temp}&quot;));
+ println!(&quot;temp: {temp}, unit: {unit}&quot;);
+
+<span style="color:red;">- let result_unit: char;</span>
+<span style="color:red;">- let result: f64 = match unit.as_str() {</span>
+<span style="color:red;">- &quot;F&quot; =&gt; {</span>
+<span style="color:red;">- result_unit = 'C';</span>
+<span style="color:red;">- fahrenheit_to_celsius(temp)</span>
+<span style="color:red;">- }</span>
+<span style="color:red;">- &quot;C&quot; =&gt; {</span>
+<span style="color:red;">- result_unit = 'F';</span>
+<span style="color:red;">- celsius_to_fahrenheit(temp)</span>
+<span style="color:red;">- }</span>
+<span style="color:lime;">+</span><span style="color:lime;"> let (result_unit, result) = match unit.as_str() {</span>
+<span style="color:lime;">+</span><span style="color:lime;"> &quot;F&quot; =&gt; ('C', fahrenheit_to_celsius(temp)),</span>
+<span style="color:lime;">+</span><span style="color:lime;"> &quot;C&quot; =&gt; ('F', celsius_to_fahrenheit(temp)),</span>
+ _ =&gt; panic!(&quot;Unknown unit {unit}&quot;),
+ };
+ println!(&quot;{temp}°{unit} = {result}°{result_unit}&quot;)
+</pre>
+
+
+#### Fibonacci
+
+```rust
+fn main() {
+ const iterations: usize = 20;
+
+ let mut prev: usize = 0;
+ let mut cur: usize = 1;
+
+ for _ in 0..iterations - 1 {
+ let temp: usize = cur;
+ cur = cur + prev;
+ println!("{prev} + {temp} = {cur}");
+ prev = temp;
+ }
+ println!("{iterations}'th fibonacci number is: {cur}");
+}
+```
+
+```console
+❮ cargo run a
+warning: constant `iterations` should have an upper case name
+ --> src/main.rs:2:11
+ |
+2 | const iterations: usize = 20;
+ | ^^^^^^^^^^
+ |
+ = note: `#[warn(non_upper_case_globals)]` (part of `#[warn(nonstandard_style)]`) on by default
+help: convert the identifier to upper case
+ |
+2 - const iterations: usize = 20;
+2 + const ITERATIONS: usize = 20;
+ |
+
+warning: `fibonacci` (bin "fibonacci") generated 1 warning (run `cargo fix --bin "fibonacci" -p fibonacci` to apply 1 suggestion)
+ Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
+ Running `target/debug/fibonacci a`
+
+❮ cargo fix --bin "fibonacci" -p fibonacci
+error: the working directory of this package has uncommitted changes, and `cargo fix` can potentially perform destructive changes; if you'd like to suppress this error pass `--allow-dirty`, or commit the changes to these files:
+
+ * .gitignore (dirty)
+ * Cargo.lock (dirty)
+ * Cargo.toml (dirty)
+ * src/ (dirty)
+
+
+    ~/projects/my_misc/rust/learning/3/fibonacci   master ?4 ─────────────────────────── ✘ 101   impure  13:54:46
+❮ cargo fix --bin "fibonacci" -p fibonacci --allow-dirty
+ Checking fibonacci v0.1.0 (/home/user/projects/my_misc/rust/learning/3/fibonacci)
+ Fixed src/main.rs (1 fix)
+ Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s
+```
+
+Again, really nice and native tooling
+
+```rust
+fn main() {
+ const ITERATIONS: usize = 20;
+
+ let mut prev: usize = 0;
+ let mut cur: usize = 1;
+
+ for _ in 0..ITERATIONS - 1 {
+ let temp: usize = cur;
+ cur = cur + prev;
+ println!("{prev} + {temp} = {cur}");
+ prev = temp;
+ }
+ println!("{ITERATIONS}'th fibonacci number is: {cur}");
+}
+```
+
+```console
+$ cargo run
+0 + 1 = 1
+1 + 1 = 2
+1 + 2 = 3
+2 + 3 = 5
+3 + 5 = 8
+5 + 8 = 13
+8 + 13 = 21
+13 + 21 = 34
+21 + 34 = 55
+34 + 55 = 89
+55 + 89 = 144
+89 + 144 = 233
+144 + 233 = 377
+233 + 377 = 610
+377 + 610 = 987
+610 + 987 = 1597
+987 + 1597 = 2584
+1597 + 2584 = 4181
+2584 + 4181 = 6765
+20'th fibonacci number is: 6765
+```
+
+Correct
+
+```
+89 1779979416004714189 + 2880067194370816120 = 4660046610375530309
+90 2880067194370816120 + 4660046610375530309 = 7540113804746346429
+91 4660046610375530309 + 7540113804746346429 = 12200160415121876738
+
+thread 'main' (266042) panicked at src/main.rs:9:15:
+attempt to add with overflow
+note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
+```
+
+Currious, if i keep running it, i outgrow the instruction set of `usize` on x86_64,
+19.740.274.219.868.223.167 > 2^64 (18,446,744,073,709,551,616)
+
+```python-console
+>>> 7540113804746346429 + 12200160415121876738
+19740274219868223167
+```
+
+Python don't care, will have to keep that in mind.
+Useful for efficiency and embedded systems.
+
+#### Twelve days of christmas
+
+```rust
+const DAYS: [&str; 12] = ["first", "second", "third", "fourth", "fifth", "sixth",
+ "seventh","eighth", "ninth", "tenth", "eleventh", "twelfth"];
+
+const THINGS: [&str; 12] = [
+ "A partridge in a pear tree",
+ "Two turtle doves and",
+ "Three french hens",
+ "Four calling birds",
+ "Five golden rings",
+ "Six geese a-laying",
+ "Seven swans a-swimming",
+ "Eight maids a-milking",
+ "Nine ladies dancing",
+ "Ten lords a-leaping",
+ "Eleven pipers piping",
+ "Twelve drummers drumming"
+];
+
+fn main() {
+ for i in 0..12 {
+ println!("On the {} day of Christmas, my true love sent to me", DAYS[i]);
+ for j in (0..i + 1).rev() {
+ println!("{}", THINGS[j]);
+ }
+ println!();
+ }
+}
+```
+
+```
+On the first day of Christmas, my true love sent to me
+A partridge in a pear tree
+
+On the second day of Christmas, my true love sent to me
+Two turtle doves and
+A partridge in a pear tree
+
+On the third day of Christmas, my true love sent to me
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the fourth day of Christmas, my true love sent to me
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the fifth day of Christmas, my true love sent to me
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the sixth day of Christmas, my true love sent to me
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the seventh day of Christmas, my true love sent to me
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the eighth day of Christmas, my true love sent to me
+Eight maids a-milking
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the ninth day of Christmas, my true love sent to me
+Nine ladies dancing
+Eight maids a-milking
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the tenth day of Christmas, my true love sent to me
+Ten lords a-leaping
+Nine ladies dancing
+Eight maids a-milking
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the eleventh day of Christmas, my true love sent to me
+Eleven pipers piping
+Ten lords a-leaping
+Nine ladies dancing
+Eight maids a-milking
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+
+On the twelfth day of Christmas, my true love sent to me
+Twelve drummers drumming
+Eleven pipers piping
+Ten lords a-leaping
+Nine ladies dancing
+Eight maids a-milking
+Seven swans a-swimming
+Six geese a-laying
+Five golden rings
+Four calling birds
+Three french hens
+Two turtle doves and
+A partridge in a pear tree
+```
+
+Again super error message for newcomers with helpful suggestion on how to remedy the issue.
+
+<pre>
+<span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:green;"> Compiling</span> twelve_days_of_christmas v0.1.0 (/home/user/projects/my_misc/rust/learning/3/twelve_days_of_christmas)
+<span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:red;">error</span><span style="font-weight:bold;">: missing type for `const` item</span>
+ <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">--&gt; </span>src/main.rs:1:12
+ <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">|</span>
+<span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">1</span> <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">|</span> const DAYS: = [&quot;first&quot;, &quot;second&quot;, &quot;third&quot;, &quot;fourth&quot;, &quot;fifth&quot;, &quot;sixth&quot;,
+ <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">|</span> <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:red;">^</span> <span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:blue;">help: provide a type for the constant: `[&amp;str; 12]`</span>
+
+<span style="font-weight:bold;"></span><span style="font-weight:bold;filter: contrast(70%) brightness(190%);color:red;">error</span>: could not compile `twelve_days_of_christmas` (bin &quot;twelve_days_of_christmas&quot;) due to 1 previous error
+</pre>
---
-### Chapter 4
+## Chapter 4