Lately, I've been studying Rust using my (tbo-in-rust
<https://github.com/edreamleo/ekr-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
--
You received this message because you are subscribed to the Google Groups
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/leo-editor/3fb17255-600d-4be0-9af1-8758c69de8ebn%40googlegroups.com.