Lately, I've been studying Rust using my (tbo-in-rust) project. This toy project transliterates Leo's token-based beautifier (leoTokens.py) into Rust.
Yesterday, I discovered a straightforward pattern that keeps Rust's borrow checker happy! This post discusses this pattern. It's both a design and coding pattern.
The pattern: Pass only immutable arguments
Methods create mutable data, but when those methods return, the rest of the program treats those data as immutable. For example, here is the beautifier's main line:
// Read the file into contents (a String).
let contents = fs::read_to_string(file_name)
.expect("Error reading{file_name}");
// Create (an immutable!) Vec of InputToks.
let input_tokens = self.make_input_list(&contents);
// The prepass creates (an immutable!) Vec of AnnotatedInputToks.
let annotated_tokens = self.annotate_tokens(&input_tokens);
// Beautify.
let results = self.beautify(&annotated_tokens);
This pattern confines mutable references within individual methods.
Aha: this pattern enforces functional programming.
Summary
Other coding patterns might keep the borrow checker happy, but a functional style seems reasonable and good.
Learning Rust has suddenly accelerated! I'm about to lose my newbie status.
Edward
P.S. The tbo-in-rust project will likely remain a toy project because the transliterated beautifier won't be significantly faster than the Python code! The culprit is RustPython's tokenizer module. It's slower than Python's!
EKR
Here are some more (perhaps last) thoughts about Rust.
Rust's language design and compiler are works of genius. The compiler often suggests the correct fix! It's been fun experiencing Rust's superb engineering.
But Rust is a language I'll admire but won't ever love. Rust excels at low-level systems programming, including Python's infrastructure. For everything else, Python expresses ideas far more clearly and with far less work.
Edward
The updated readme file discusses the status of the tbo-in-rust project. The project is at a good stopping point, but I might press on a bit more.