To familiarize myself with Rust in 2022 I ported a small Javascript SPA that originates from around 2012. In essence, the goal was, how would I do "X" (functions, xhr, parsing, regex, events, etc.) in Rust?
To get around some scoping issues, I updated the JS as I was doing the Rust port. This was done so I can keep the code near to 1:1 as possible.
The port is done, and it works (both JS and Rust implementations). But I have questions:
The SPA? Reads a text file (with pairs of quoted strings), fetches some data, and creates a slideshow.
Updated JS:
Rust Port:
Questions:
-
Globals: In Rust it seems like I couldn't create a global object to namespace and store all my values/references. So in both the JS and Rust code I created a custom prototype/type, dumped all my methods/variables/states into that, initialized it for use, and passed that throughout the code. Is there a better/simpler way of holding/referencing mutable values for use in functions other than by passing it around?
-
Use of
static
/Atomic
(globals): Supposedlystatic
/Atomic
is not to be relied on (inefficient ?). Is there a better way of sharing a non-complex mutable value between functions, without passing it around? -
Unwrap
orMatch
+OK
+Err
(verbosity): Earlier versions of the Rust code usedUnwrap
everywhere. However I have seen suggestions thatMatch
+OK
+Err
is better. What is the consensus on this? -
Closures >>> Cloning (verbosity): Everywhere I closed over a value I ended up having to clone the value in Rust to keep the compiler happy (lifetimes). Is there a way to do closures in Rust without cloning?
-
Parameter exhaustion. (syntax): For me, the increase in function parameters increased the headache of debugging compiler errors (e.g. passed it once? ha ha, gotta pass it everywhere now). I crammed a lot into my custom type and passed that blob around, but ideally, I would like to pass less stuff, and just reference an 'external' set of types/values/etc. Is that possible?
-
Sometimes mut, sometimes not (syntax): For me it was odd that some functions were OK with
arg: &Type
being passed but others needingarg: &mut Type
. I realized that the functions that might modifyType
required the mut (i.e. contains anif
statement), but it seems I'm rewriting/summarizing every function inside the arguments/parameter signature. Is this just the way things are in strongly-typed languages?