My Website

Main website: show.admoss.info

Wednesday, December 20, 2023

Rust - the programming language

My latest adventure in computer languages is Rust.

Rust is billed as the "most loved" computer language. Those who use Rust are certainly passionate about it. Jealous too. I found most of the tutorials on the major Rust frameworks have bugs that require fixing for the examples to run. Fixing them requires a level of familiarity you can only gain with experience. Without the tutorials, and lacking the experience to fix them, newbies are effectively locked out.

I read through the book The Rust Programming Language and did the exercises while I was on holiday in Norway. (I did have a full holiday itinerary and only studied Rust while my partner was busy with mail in the evenings) I found it a good start to the language.

One feature of Rust is the way the compiler will not allow anything through that may cause a runtime error. If you try, the program will simply not compile. This can be frustrating to a newbie, but it makes Rust one of the safest languages available.

Rust has no garbage collector. That makes the programmer responsible for managing memory, but completely eliminates memory leaks. It has a concept of variable ownership that makes memory management simple, once you get used to it.

Variables are immutable (can't be changed) by default. If you want them to be mutable you have to prefix them with the mut keyword. Variables are owned by the scope in which they are created and deleted when that scope ends. If they are sent to another scope, the new scope becomes the owner, and they can no longer be used in the original scope. When the new scope ends the variable is deleted from memory. This issue is circumvented by lending the variable to the new scope (say, a function) using the & prefix. Until you get used to it variable lending and borrowing can be confusing. But it eliminates race conditions where more than one thread tries to modify a variable at the same time. Definitely a good thing.

Once I had the basics under control, I dipped my toe in some of the web frameworks available for Rust. Functionality is included in Rust programs by adding crates. A crate is a package of Rust code that can easily be included via the use keyword.

Another feature is the ability to compile Rust to almost any target. Windows, Linux and MacOs are obvious targets, as are Android and iOS. Compilers also exist for Arduino and many other microcontrollers. The most astounding target is WebAssembly. Rust can be compiled to wasm that can run at near native speed in most modern web browsers. This brings the term "write once, run anywhere" closer to reality than ever before.

My way forward with Rust is to write a web application using  leptos and axum. This combination will build a back-end web server in native code and a front-end user interface in WebAssembly that interact safely. All written in Rust.


No comments: