# Rust (Language)

## Summary


C and C++ are highly performant and offer low-level control, which is something systems programmers want. But they're not safe since it's easy to access wrong memory locations. Haskell is a lot safer but it doesn't offer low-level control. Go and Java are somewhere in between. In all these languages, trade-offs have been made. Rust is a programming language that's safe, performant, and offers low-level control. 

Rust achieves this with strong static typing and compile-time checks. Many problems are caught at compile time rather than at runtime. The concept of ownership leads to memory-safe and thread-safe code. Rust itself is considered a multi-paradigm language with design elements taken from many other languages. 

Rust is open source and overseen by the Rust Foundation.

## Discussion

### For what use cases is Rust suitable?

**Systems programming** is the main use case for Rust. Systems programming includes operating systems, file systems, and low-level drivers. We can also include any code that powers other applications, such as web browsers, web frameworks, and game engines. For systems programming, it's important to have safe memory management without runtime overhead. Untrusted code shouldn't be allowed to cause problems. We want low-level access so that we can optimize our code for time and space. 

Rust is well-suited for **embedded development**. It can run on bare-metal systems without any RTOS. Pin and peripheral configurations can be enforced at compile time. We can choose to leave out the heap and allocate all memory statically. Concurrency is easy to achieve since Rust ensures that two threads will not accidentally share state. Interoperability and portability are other benefits. 

Rust is capable of providing performance close to that of C++. Hence it's seen as a language for **High-Performance Computing (HPC)** and scientific computing. 

The Rust community is also adopting Rust in a variety of areas including web development, distributed peer-to-peer computing, game development, GUI development, machine learning, quantum computing, audio processing, and more. 


### Which are main design aspects of Rust?

**Ownership** is Rust's most unique feature. Each value can have only one owner. The value is dropped when the owner goes out of scope. Scope is implemented by another feature called **lifetime**. These bring memory safety to Rust programs. Heap memory is safely allocated and deallocated even without a garbage collector. Ownership can be borrowed or moved. For thread-safe code, Rust a thread can borrow ownership from another thread, thus preventing data races. 

Most problems in Rust code are caught at **compile time**. As a result, runtime overheads are less. Rust abstractions are not expected to add overhead to equivalent low-level code. Rust calls this **zero-cost abstractions**. Rust doesn't support NULL pointers like in C/C++. Error handling is possible but there's no support for exceptions. Again, the philosophy is to catch most things at compile time. 

Variables are **immutable** by default to promote safe coding. Another type-safe feature is that function parameters must include **type annotations**. 


### Which are the basic programming constructs available in Rust?

Like most languages, Rust specifies language keywords, variables, data types, functions, function parameters, control flow, expressions, statements and comments. Scalar types include signed/unsigned integers, floating-point numbers, Booleans, and characters. Compound types include tuples and arrays, both of fixed length. Tuples can contain items of different types but array items must be of the same type. Data structures called *collections* are allocated on the heap. Vectors, strings and hash maps are examples. 

Custom data types can be defined using `struct` and `enum`. In `struct` definitions we can include associated behaviour using *methods*. With `enum`, we can use the `match` expression to implement powerful behaviours including the `switch-case` construct common in other languages. Generics and traits enable reusable types and behaviours respectively. 

A function can accept arguments and can return a value. Anonymous functions can be assigned to variables and passed around. Code blocks (including function bodies) are defined within `{…}`. Control expressions include `if-else`, `while`, `loop`, `if-let` and `while-let`. However, parentheses are rarely used around these expressions. 


### Is Rust an object-oriented or a functional language?

Rust combines some aspects of both object-oriented and functional programming paradigms. 

Rust provides `struct` and `enum` types that contain data and behaviour. Behaviour is specified using `impl` blocks. Rust provides encapsulation at many levels: modules, types, functions and methods. By default these are private and they're made public using `pub` keyword. Thus, developers can change internal implementations without affecting their users who use the public API. 

Inheritance is widely used in OOP but this is not supported in Rust. However, Rust uses traits to achieve code reuse. Trait objects help achieve dynamic dispatch or polymorphism. In fact, trait objects are closer to OOP's objects. 

Rust's `enum` and associated pattern matching are similar to algebraic data types seen in functional languages. Closures are supported, that is, we can define anonymous functions that capture their environments, save them into variables and use as function arguments. The use of iterators to process a sequence of items is also influenced by functional programming. 


### Who has adopted Rust so far?

Apart from Mozilla that created Rust, the language has been adopted by many companies including Dropbox, Coursera, Figma, npm, Microsoft, Cloudflare, Facebook, Amazon and Discord. Adoption spans standalone software, cloud-hosted software, edge software and even embedded devices.  

Dropbox preferred Rust's compile-time checks on static types over Python's dynamic typing. Rust provided high concurrency required by their file synchronization engine. At Coursera, user-submitted code is executed within Docker containers. Being a low-level and type-safe language, Rust offered Coursera more security than C. Figma rewrote its multiplayer syncing engine in Rust for better performance because the older TypeScript code suffered from garbage collection. At Discord, Rust is used for both client-side (via WASM) and server-side logic. Cloudflare is preferring Rust over C at the cloud edge because of its better memory safety. 

Facebook's source control team chose Rust over C++ for its higher reliability. By 2019, Rust was widely adopted in Facebook, first for developer tooling and later for small services. 

For embedded development, many RTOSes, CPU architectures and boards offer APIs for Rust. Sensirion, Airborne Engineering Ltd. and 49nord are some adopters in the embedded space. 


### What are some criticisms of Rust?

Rust has its fair share of criticism. Among them are its complex syntax and a steep learning curve; slow compilations; limited choice of compilers and target architectures compared to C; limited tooling; limited or immature third-party libraries; unsafe and difficult integrations with other languages. Developers can misuse `unsafe` blocks. While its positioned as a systems programming language, not every programming is of this nature.  

Rust is too verbose with syntax such as `Vec<Rc<RefCell<Box<Trait>>>>`. There are five types of pointers and it's not trivial to select the right one. Rust lacks a strict description of its semantics. This means that formal verification is not possible. The use of downloadable crates can lead to complex dependency trees. Some consider Rust macros a design mistake or an afterthought to cover up other mistakes.  

While performant, Rust is not much better than Go, Java, Scala or Haskell. While C++ is not type safe like Rust, C++ has many static and dynamic analyzers to achieve this. C continues to be better in many aspects: highly portable, formally specified, many implementations, stable ABI. For concurrency and simplicity, some developers prefer Go.  


### What tools are available for Rust programming?

Rust tooling is improving all the time. Beginners can note the following:

    + **Installation**: Rust can be installed or updated using `rustup`. This can also install optional components such as `clippy` (linter) and `rustfmt` (code formatter).
    + **Compiler**: The main compiler for Rust is `rustc`. It's based on LLVM compiler toolchain and therefore can target various architectures already supported by LLVM.  The executable program or package at the output of the compiler is called a *crate*. The tool `sccache` can reduce compile times.
    + **IDE**: VSCode, IntelliJ and Vim are some IDEs that support Rust, often via the Rust Language Server (RLS).
    + **Package Manager**: Projects typically have dependencies. *Cargo* is the package manager that fetches project dependencies from a central repository. Cargo is also a build system. After downloading the right packages, it can invoke the `rustc` compiler.
    + **Package Registry**: Crates are typically published at `crates.io`. By default, Cargo searches `crates.io` for dependent packages.
    + **Documentation**: The tool for this is `rustdoc`, which can also be invoked using Cargo. Documentation is generated from doc comments in source files or standalone Markdown files.


## Milestones

2006

Graydon Hoare at Mozilla, who usually works on compilers and tools, starts working on Rust as a hobby project. Later, when he shows this to his manager, Mozilla takes interest in this new language. The idea is to see if Rust could be used to rewrite their browser stack in a more safer and more concurrent way than possible with C++. In a later interview, Hoare notes that Rust's target audience was "frustrated C++ developers". 

2009

Mozilla begins sponsoring the development of Rust. Rust is announced to the world in 2010.  

2010

A bootstrap **compiler** for Rust becomes available. In 2011, a self-hosted compiler appears. In 2012, 0.3 alpha release of the compiler appears. 

Mar  
2014

Inspired by Python's PEP, Rust adopts an **RFC process**. Major changes to the language must go through this process. By June 2016, 1632 proposals are submitted, 243 are accepted and 69 are open. 

May  
2015

**Rust 1.0** is released as the first stable version of the language. 

Nov  
2017

Mozilla's Firefox Quantum now uses a CSS engine written entirely in Rust. Called *Stylo*, it replaces 160,000 lines of C++ with 85,000 lines of Rust. Due to Rust's excellent support for concurrency, the new engine speeds up page styling. Styling of child DOM elements is done concurrently. Developers could write code without worrying too much about safety. They found Rust's panics easier to deal with than C++ segmentation faults. 

2020

In the annual StackOverflow developer survey, Rust is the **most-loved programming language** for the fifth year in a row. These are from survey participants who use Rust and will continue to use it. Rust is in fifth position as the most-wanted language. In July, Rust rises to 18th place in the TIOBE index from 33rd place just a year earlier. 

Feb  
2021

**The Rust Foundation** is formed with Mozilla coming in as a Platinum Sponsor. It's expected that the board will represent various stakeholders. 

Apr  
2021

In an article on TechRepublic, Matt Asay writes that it's Rust, not Firefox, that's Mozilla's most important contribution to the world of technology. 

Aug  
2021

Fulton et al. share results of a survey of 178 Rust developers. While developers like many of Rust's features that lead to safer code, they complain about long compile times, long time to prototype, and poor debugging tools.