Rust (programming language)

Rust
A capitalized letter R set into a sprocket
The official Rust logo
Paradigms
Designed byGraydon Hoare
DeveloperRust Foundation
First appearedMay 15, 2015; 8 years ago (2015-05-15)
Stable release
1.75.0 Edit this on Wikidata / December 28, 2023; 36 days ago (December 28, 2023)
Typing discipline
Implementation languageRust
PlatformCross-platform
OSCross-platform
LicenseMIT and Apache 2.0
Filename extensions.rs, .rlib
Websitewww.rust-lang.org
Influenced by
Influenced

Rust is a multi-paradigm, general-purpose programming language that emphasizes performance, type safety, and concurrency. It enforces memory safety—meaning that all references point to valid memory—without a garbage collector. To simultaneously enforce memory safety and prevent data races, its "borrow checker" tracks the object lifetime of all references in a program during compilation. Rust was influenced by ideas from functional programming, including immutability, higher-order functions, and algebraic data types. It is popular for systems programming.

Software developer Graydon Hoare created Rust as a personal project while working at Mozilla Research in 2006. Mozilla officially sponsored the project in 2009. In the years following the first stable release in May 2015, Rust was adopted by companies including Amazon, Discord, Dropbox, Google (Alphabet), Meta, and Microsoft. In December 2022, it became the first language other than C and assembly to be supported in the development of the Linux kernel.

Rust has been noted for its rapid adoption, and has been studied in programming language theory research. The name comes from the Rust fungus. The Rust logo is based on a bike chain ring because Graydon Hoare and other developers liked to ride bikes..

History

Mozilla Foundation headquarters in Mountain View, California

Origins (2006–2012)

Rust grew out of a personal project begun in 2006 by Mozilla Research employee Graydon Hoare. Mozilla began sponsoring the project in 2009 as a part of the ongoing development of an experimental browser engine called Servo, which was officially announced by Mozilla in 2010. During the same year, work shifted from the initial compiler written in OCaml to a self-hosting compiler based on LLVM written in Rust. The new Rust compiler successfully compiled itself in 2011.

Evolution (2012–2019)

Rust's type system underwent significant changes between versions 0.2, 0.3, and 0.4. In version 0.2, which was released in March 2012, classes were introduced for the first time. Four months later, version 0.3 added destructors and polymorphism, through the use of interfaces. In October 2012, version 0.4 was released, which added traits as a means of inheritance. Interfaces were combined with traits and removed as a separate feature; and classes were replaced by a combination of implementations and structured types.

Through the early 2010s, memory management through the ownership system was gradually consolidated to prevent memory bugs. By 2013, Rust's garbage collector was removed, with the ownership rules in place.

In January 2014, the editor-in-chief of Dr. Dobb's Journal, Andrew Binstock, commented on Rust's chances of becoming a competitor to C++, along with D, Go, and Nim (then Nimrod). According to Binstock, while Rust was "widely viewed as a remarkably elegant language", adoption slowed because it radically changed from version to version. The first stable release, Rust 1.0, was announced on May 15, 2015.

The development of the Servo browser engine continued alongside Rust's own growth. In September 2017, Firefox 57 was released as the first version that incorporated components from Servo, in a project named "Firefox Quantum".

Mozilla layoffs and Rust Foundation (2020–present)

In August 2020, Mozilla laid off 250 of its 1,000 employees worldwide, as part of a corporate restructuring caused by the COVID-19 pandemic. The team behind Servo was disbanded. The event raised concerns about the future of Rust, as some members of the team were active contributors to Rust. In the following week, the Rust Core Team acknowledged the severe impact of the layoffs and announced that plans for a Rust foundation were underway. The first goal of the foundation would be to take ownership of all trademarks and domain names, and take financial responsibility for their costs.

On February 8, 2021, the formation of the Rust Foundation was announced by its five founding companies (AWS, Huawei, Google, Microsoft, and Mozilla). In a blog post published on April 6, 2021, Google announced support for Rust within the Android Open Source Project as an alternative to C/C++.

On November 22, 2021, the Moderation Team, which was responsible for enforcing community standards and the Code of Conduct, announced their resignation "in protest of the Core Team placing themselves unaccountable to anyone but themselves". In May 2022, the Rust Core Team, other lead programmers, and certain members of the Rust Foundation board implemented governance reforms in response to the incident.

The Rust Foundation posted a draft for a new trademark policy on April 6, 2023, revising its rules on how the Rust logo and name can be used, which resulted in negative reactions from Rust users and contributors.

Syntax and features

Rust's syntax is similar to that of C and C++, although many of its features were influenced by functional programming languages. Hoare described Rust as targeted at "frustrated C++ developers" and emphasized features such as safety, control of memory layout, and concurrency. Safety in Rust includes the guarantees of memory safety, type safety, and lack of data races.

Hello World program

Below is a "Hello, World!" program in Rust. The fn keyword denotes a function, and the println! macro prints the message to standard output. Statements in Rust are separated by semicolons.

fn main(){
println!("Hello, World!");
}

Keywords and control flow

In Rust, blocks of code are delimited by curly brackets, and control flow is implemented by keywords such as if, else, while, and for. Pattern matching can be done using the match keyword. In the examples below, explanations are given in comments, which start with //.

fn main(){
// Defining a mutable variable with 'let mut'
// Using the macro vec! to create a vector
letmutvalues=vec![1,2,3,4];

forvaluein&values{
println!("value = {}",value);
}

ifvalues.len()>5{
println!("List is longer than five items");
}

// Pattern matching
matchvalues.len(){
0=>println!("Empty"),
1=>println!("One value"),
// pattern matching can use ranges of integers
2..=10=>println!("Between two and ten values"),
11=>println!("Eleven values"),
// A `_` pattern is called a "wildcard", it matches any value
_=>println!("Many values"),
};

// while loop with predicate and pattern matching using let
whileletSome(value)=values.pop(){
println!("value = {value}");// using curly brackets to format a local variable
}
}

Expression blocks

Rust is expression-oriented, with nearly every part of a function body being an expression, including control-flow operators. The ordinary if expression is used instead of C's ternary conditional. With returns being implicit, a function does not need to end with a return expression; if the semicolon is omitted, the value of the last expression in the function is used as the return value, as seen in the following recursive implementation of the factorial function:

fn factorial(i: u64)-> u64 {
ifi==0{
1
}else{
i*factorial(i-1)
}
}

The following iterative implementation uses the ..= operator to create an inclusive range:

fn factorial(i: u64)-> u64 {
(2..=i).product()
}

Closures

In Rust, anonymous functions are called closures. They are defined using the following syntax:

|<parameter-name>: <type>|-> <return-type>{<body>};

For example:

letf=|x: i32|-> i32 {x*2};

With type inference, however, the compiler is able to infer the type of each parameter and the return type, so the above form can be written as:

letf=|x|{x*2};

With closures with a single expression (i.e. a body with one line) and implicit return type, the curly braces may be omitted:

letf=|x|x*2;

Closures with no input parameter are written like so:

letf=||println!("Hello, world!");

Closures may be passed as input parameters of functions that expect a function pointer:

// A function which takes a function pointer as an argument and calls it with
// the value `5`.
fn apply(f: fn(i32)-> i32)-> i32 {
// No semicolon, to indicate an implicit return
f(5)
}

fn main(){
// Defining the closure
letf=|x|x*2;

println!("{}",apply(f));// 10
println!("{}",f(5));// 10
}

However, one may need complex rules to describe how values in the body of the closure are captured. They are implemented using the Fn, FnMut, and FnOnce traits:

  • Fn: the closure captures by reference (&T). They are used for functions that can still be called if they only have reference access (with &) to their environment.
  • FnMut: the closure captures by mutable reference (&mut T). They are used for functions that can be called if they have mutable reference access (with &mut) to their environment.
  • FnOnce: the closure captures by value (T). They are used for functions that are only called once.

With these traits, the compiler will capture variables in the least restrictive manner possible. They help govern how values are moved around between scopes, which is largely important since Rust follows a lifetime construct to ensure values are "borrowed" and moved in a predictable and explicit manner.

The following demonstrates how one may pass a closure as an input parameter using the Fn trait:

// A function that takes a value of type F (which is defined as
// a generic type that implements the `Fn` trait, e.g. a closure)
// and calls it with the value `5`.
fn apply_by_ref<F>(f: F)-> i32
    whereF: Fn(i32)-> i32
{
f(5)
}

fn main(){
letf=|x|{
println!("I got the value: {}",x);
x*2
};

// Applies the function before printing its return value
println!("5 * 2 = {}",apply_by_ref(f));
}

// ~~ Program output ~~
// I got the value: 5
// 5 * 2 = 10

The previous function definition can also be shortened for convenience as follows:

fn apply_by_ref(f: implFn(i32)-> i32)-> i32 {
f(5)
}

Types

Rust is strongly typed and statically typed. The types of all variables must be known at compilation time; assigning a value of a particular type to a differently typed variable causes a compilation error. Variables are declared with the keyword let, and type inference is used to determine their type. Variables assigned multiple times must be marked with the keyword mut (short for mutable).

The default integer type is i32, and the default floating point type is f64. If the type of a literal number is not explicitly provided, either it is inferred from the context or the default type is used.

Primitive types

Summary of Rust's Primitive Types
Type Description Examples
bool Boolean value
  • true
  • false
u8 Unsigned 8-bit integer (a byte)
  • 255u8
  • b'W' (ASCII encoded byte)
  • i8
  • i16
  • i32
  • i64
  • i128
Signed integers, up to 128 bits
  • 7
  • 7i128
  • u16
  • u32
  • u64
  • u128
Unsigned integers, up to 128 bits
  • 14
  • 14u128
  • usize
  • isize
Pointer-sized integers (size depends on platform)
  • 14usize
  • -2isize
  • f32
  • f64
Floating-point numbers
  • -3f32
char
str UTF-8-encoded string slice, the primitive string type. It is usually seen in its borrowed form, &str. It is also the type of string literals, &'staticstr
  • "Hello"
  • "3"
  • "🦀🦀🦀"
[T;N] Array – collection of N objects of the same type T, stored in contiguous memory
  • [2,4,6]
  • [0;100]
  • b"Hello"
[T] Slice – a dynamically-sized view into a contiguous sequence
  • [1,2,3,4,5][..i]
  • "Hello, world!".as_bytes()
  • letv=vec![1,2,3];v.as_slice()
(T,U,..)
Tuple – a finite heterogeneous sequence
  • () (An empty tuple, the unit type in Rust)
  • (5,) ((5) is parsed as an integer)
  • ("Age",10)
  • (1,true,"Name")
! Never type (unreachable value) letx={return123};

Standard library

Summary of Rust's types in the standard library
Type Description Examples
Box<T> A pointer to a heap-allocated value
letboxed: Box<u8>=Box::new(5);
letval: u8 =*boxed;
String UTF-8-encoded strings (dynamic)
  • String::new()
  • String::from("Hello")
  • "🦀🦀🦀".to_string()
  • OsStr
  • OsString
Platform-native strings (borrowed and dynamic)
  • OsStr::new("Hello")
  • OsString::from("world")
  • Path
  • PathBuf
Paths (borrowed and dynamic)
  • Path::new("./path/to")
  • PathBuf::from(r"C:.\path\to")
  • CStr
  • CString
C-compatible, null-terminated strings (borrowed and dynamic)
  • CStr::from_bytes_with_nul(b"Hello\0").unwrap()
  • CString::new("world").unwrap()
Vec<T> Dynamic arrays
  • Vec::new()
  • vec![1,2,3,4,5]
Option<T> Option type
  • None
  • Some(3)
  • Some("hello")
Result<T,E> Error handling using a result type
  • Ok(3)
  • Err("something went wrong")
Rc<T> Reference counting pointer
letfive=Rc::new(5);
letalso_five=five.clone();
Arc<T> Atomic, thread-safe reference counting pointer
letfoo=Arc::new(vec![1.0,2.0]);
leta=foo.clone();// a can be sent to another thread
Cell<T> A mutable memory location
letc=Cell::new(5);
c.set(10);
Mutex<T> A mutex lock for shared data
letmutex=Mutex::new(0_u32);
let_guard=mutex.lock();
RwLock<T> Readers–writer lock
letlock=RwLock::new(5);
letr1=lock.read().unwrap();
Condvar A conditional monitor for shared data
let(lock,cvar)=(Mutex::new(true),Condvar::new());
// As long as the value inside the `Mutex<bool>` is `true`, we wait.
let_guard=cvar.wait_while(lock.lock().unwrap(),|pending|{*pending}).unwrap();
Duration Type that represents a span of time
Duration::from_millis(1)// 1ms
HashMap<K,V> Hash table
letmutplayer_stats=HashMap::new();
player_stats.insert("damage",1);
player_stats.entry("health").or_insert(100);
BTreeMap<K,V> B-tree
letmutsolar_distance=BTreeMap::from([
("Mercury",0.4),
("Venus",0.7),
]);
solar_distance.entry("Earth").or_insert(1.0);

Option values are handled using syntactic sugar, such as the if let construction, to access the inner value (in this case, a string):

fn main(){
letname1: Option<&str>=None;
// In this case, nothing will be printed out
ifletSome(name)=name1{
println!("{name}");
}

letname2: Option<&str>=Some("Matthew");
// In this case, the word "Matthew" will be printed out
ifletSome(name)=name2{
println!("{name}");
}
}

Pointers

Summary of Rust's pointer and reference primitive types
Type Description Examples
  • &T
  • &mutT
References (immutable and mutable)
  • letx_ref=&x;
  • letx_ref=&mutx;
  • Option<&T>
  • Option<&mutT>
  • Option wrapped reference
  • Possibly null reference
  • None
  • letx_ref=Some(&x);
  • letx_ref=Some(&mutx);
  • Box<T>
  • Option<Box<T>>
A pointer to heap-allocated value

(or possibly null pointer if wrapped in option)

  • letboxed=Box::new(0);
  • letboxed=Some(Box::new("Hello World"));
  • *constT
  • *mutT
  • letx_ptr=&xas*constT;
  • letx_ptr=&mutxas*mutT;

Rust does not use null pointers to indicate a lack of data, as doing so can lead to null dereferencing. Accordingly, the basic & and &mut references are guaranteed to not be null. Rust instead uses Option for this purpose: Some(T) indicates that a value is present, and None is analogous to the null pointer. Option implements a "null pointer optimization", avoiding any spatial overhead for types that cannot have a null value (references or the NonZero types, for example).

Unlike references, the raw pointer types *const and *mut may be null; however, it is impossible to dereference them unless the code is explicitly declared unsafe through the use of an unsafe block. Unlike dereferencing, the creation of raw pointers is allowed inside of safe Rust code.

User-defined types

User-defined types are created with the struct or enum keywords. The struct keyword is used to denote a record type that groups multiple related values. enums can take on different variants at runtime, with its capabilities similar to algebraic data types found in functional programming languages. Both structs and enums can contain fields with different types. Alternative names for the same type can be defined with the type keyword.

The impl keyword can define methods for a user-defined type (data and functions are defined separately). Implementations fulfill a role similar to that of classes within other languages.

Type conversion

Rust provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as keyword.

letx=1000;
println!("1000 as a u16 is: {}",xasu16);

Ownership and lifetimes

Rust's ownership system consists of rules that ensure memory safety without using a garbage collector. At compile time, each value must be attached to a variable called the owner of that value, and every value must have exactly one owner. Values are moved between different owners through assignment or passing a value as a function parameter. Values can also be borrowed, meaning they are temporarily passed to a different function before being returned to the owner. With these rules, Rust can prevent the creation and use of dangling pointers:

fn print_string(s: String){
println!("{}",s);
}

fn main(){
lets=String::from("Hello, World");
print_string(s);// s consumed by print_string
// s has been moved, so cannot be used any more
// another print_string(s); would result in a compile error
}

Because of these ownership rules, Rust types are known as linear or affine types, meaning each value can be used exactly once. This enforces a form of software fault isolation as the owner of a value is solely responsible for its correctness and deallocation.

Lifetimes are usually an implicit part of all reference types in Rust. Each lifetime encompasses a set of locations in the code for which a variable is valid. For example, a reference to a local variable has a lifetime corresponding to the block it is defined in:

fn main(){
letr=9;// ------------------+- Lifetime 'a
//                   |
{//                   |
letx=5;// -+-- Lifetime 'b  |
println!("r: {}, x: {}",r,x);//  |                |
}//  |                |
//                   |
println!("r: {}",r);//                   |
}// ------------------+

The borrow checker in the Rust compiler uses lifetimes to ensure that the values a reference points to remain valid. It also ensures that a mutable reference exists only if no immutable references exist at the same time. In the example above, the subject of the reference (variable x) has a shorter lifetime than the lifetime of the reference itself (variable r), therefore the borrow checker errors, preventing x from being used from outside its scope. Rust's memory and ownership system was influenced by region-based memory management in languages such as Cyclone and ML Kit.

Rust defines the relationship between the lifetimes of the objects created and used by functions, using lifetime parameters, as a signature feature.

When a stack or temporary variable goes out of scope, it is dropped by running its destructor. The destructor may be programmatically defined through the drop function. This technique enforces the so-called resource acquisition is initialization (RAII) design pattern, in which resources, such as file descriptors or network sockets, are tied to the lifetime of an object: when the object is dropped, the resource is closed.

The example below parses some configuration options from a string and creates a struct containing the options. The struct only contains references to the data; so, for the struct to remain valid, the data referred to by the struct must be valid as well. The function signature for parse_config specifies this relationship explicitly. In this example, the explicit lifetimes are unnecessary in newer Rust versions, due to lifetime elision, which is an algorithm that automatically assigns lifetimes to functions if they are trivial.

usestd::collections::HashMap;

// This struct has one lifetime parameter, 'src. The name is only used within the struct's definition.
#[derive(Debug)]
struct Config<'src>{
hostname: &'src str,
username: &'src str,
}

// This function also has a lifetime parameter, 'cfg. 'cfg is attached to the "config" parameter, which
// establishes that the data in "config" lives at least as long as the 'cfg lifetime.
// The returned struct also uses 'cfg for its lifetime, so it can live at most as long as 'cfg.
fn parse_config<'cfg>(config: &'cfg str)-> Config<'cfg>{
letkey_values: HashMap<_,_>=config
.lines()
.filter(|line|!line.starts_with('#'))
.filter_map(|line|line.split_once('='))
.map(|(key,value)|(key.trim(),value.trim()))
.collect();
Config{
hostname: key_values["hostname"],
username: key_values["username"],
}
}

fn main(){
letconfig=parse_config(
r#"hostname = foobar
username=barfoo"#,
);
println!("Parsed config: {:#?}",config);
}
A presentation on Rust by Emily Dunham from Mozilla's Rust team (linux.conf.au conference, Hobart, 2017)

Memory safety

Rust is designed to be memory safe. It does not permit null pointers, dangling pointers, or data races. Data values can be initialized only through a fixed set of forms, all of which require their inputs to be already initialized.

Unsafe code can subvert some of these restrictions, using the unsafe keyword. Unsafe code may also be used for low-level functionality, such as volatile memory access, architecture-specific intrinsics, type punning, and inline assembly.

Memory management

Rust does not use garbage collection. Memory and other resources are instead managed through the "resource acquisition is initialization" convention, with optional reference counting. Rust provides deterministic management of resources, with very low overhead. Values are allocated on the stack by default, and all dynamic allocations must be explicit.

The built-in reference types using the & symbol do not involve run-time reference counting. The safety and validity of the underlying pointers is verified at compile time, preventing dangling pointers and other forms of undefined behavior. Rust's type system separates shared, immutable references of the form &T from unique, mutable references of the form &mut T. A mutable reference can be coerced to an immutable reference, but not vice versa.

Polymorphism

Generics

Rust's more advanced features include the use of generic functions. A generic function is given generic parameters, which allow the same function to be applied to different variable types. This capability reduces duplicate code and is known as parametric polymorphism.

The following program calculates the sum of two things, for which addition is implemented using a generic function:

usestd::ops::Add;

// sum is a generic function with one type parameter, T
fn sum<T>(num1: T,num2: T)-> T
where
T: Add<Output=T>,// T must implement the Add trait where addition returns another T
{
num1+num2// num1 + num2 is syntactic sugar for num1.add(num2) provided by the Add trait
}

fn main(){
letresult1=sum(10,20);
println!("Sum is: {}",result1);// Sum is: 30

letresult2=sum(10.23,20.45);
println!("Sum is: {}",result2);// Sum is: 30.68
}

At compile time, polymorphic functions like sum are instantiated with the specific types the code requires; in this case, sum of integers and sum of floats.

Generics can be used in functions to allow implementing a behavior for different types without repeating the same code. Generic functions can be written in relation to other generics, without knowing the actual type.

Traits

Rust's type system supports a mechanism called traits, inspired by type classes in the Haskell language, to define shared behavior between different types. For example, the Add trait can be implemented for floats and integers, which can be added; and the Display or Debug traits can be implemented for any type that can be converted to a string. Traits can be used to provide a set of common behavior for different types without knowing the actual type. This facility is known as ad hoc polymorphism.

Generic functions can constrain the generic type to implement a particular trait or traits; for example, an add_one function might require the type to implement Add. This means that a generic function can be type-checked as soon as it is defined. The implementation of generics is similar to the typical implementation of C++ templates: a separate copy of the code is generated for each instantiation. This is called monomorphization and contrasts with the type erasure scheme typically used in Java and Haskell. Type erasure is also available via the keyword dyn (short for dynamic). Because monomorphization duplicates the code for each type used, it can result in more optimized code for specific-use cases, but compile time and size of the output binary are also increased.

In addition to defining methods for a user-defined type, the impl keyword can be used to implement a trait for a type. Traits can provide additional derived methods when implemented. For example, the trait Iterator requires that the next method be defined for the type. Once the next method is defined, the trait can provide common functional helper methods over the iterator, such as map or filter.

Traits follow the composition over inheritance design principle. That is, traits cannot define fields themselves; they provide a restricted form of inheritance where methods can be defined and mixed in to implementations.

Trait objects

Rust traits are implemented using static dispatch, meaning that the type of all values is known at compile time; however, Rust also uses a feature known as trait objects to accomplish dynamic dispatch (also known as duck typing). Dynamically dispatched trait objects are declared using the syntax dyn Tr where Tr is a trait. Trait objects are dynamically sized, therefore they must be put behind a pointer, such as Box. The following example creates a list of objects where each object can be printed out using the Display trait:

usestd::fmt::Display;

letv: Vec<Box<dynDisplay>>=vec![
Box::new(3),
Box::new(5.0),
Box::new("hi"),
];

forxinv{
println!("{x}");
}

If an element in the list does not implement the Display trait, it will cause a compile-time error.

Iterators

For loops in Rust work in a functional style as operations over an iterator type. For example, in the loop

forxin0..100{
f(x);
}

0..100 is a value of type Range which implements the Iterator trait; the code applies the function f to each element returned by the iterator. Iterators can be combined with functions over iterators like map, filter, and sum. For example, the following adds up all numbers between 1 and 100 that are multiples of 3:

(1..=100).filter(|&x|x%3==0).sum()

Macros

It is possible to extend the Rust language using macros.

Declarative macros

A declarative macro (also called a "macro by example") is a macro that uses pattern matching to determine its expansion.

Procedural macros

Procedural macros are Rust functions that run and modify the compiler's input token stream, before any other components are compiled. They are generally more flexible than declarative macros, but are more difficult to maintain due to their complexity.

Procedural macros come in three flavors:

  • Function-like macros custom!(...)
  • Derive macros #[derive(CustomDerive)]
  • Attribute macros #[custom_attribute]

The println! macro is an example of a function-like macro. Theserde_derive macro provides a commonly used library for generating code for reading and writing data in many formats, such as JSON. Attribute macros are commonly used for language bindings, such as the extendr library for Rust bindings to R.

The following code shows the use of the Serialize, Deserialize, and Debug-derived procedural macros to implement JSON reading and writing, as well as the ability to format a structure for debugging.

A UML diagram depicting a Rust struct named Point.
useserde_json::{Serialize,Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point{
x: i32,
y: i32,
}

fn main(){
letpoint=Point{x: 1,y: 2};

letserialized=serde_json::to_string(&point).unwrap();
println!("serialized = {}",serialized);

letdeserialized: Point=serde_json::from_str(&serialized).unwrap();
println!("deserialized = {:?}",deserialized);
}

Variadic macros

Rust does not support variadic arguments in functions. Instead, it uses macros.

macro_rules!calculate{
// The pattern for a single `eval`
(eval$e:expr)=>{{
{
letval: usize =$e;// Force types to be integers
println!("{} = {}",stringify!{$e},val);
}
}};

// Decompose multiple `eval`s recursively
(eval$e:expr,$(eval$es:expr),+)=>{{
calculate!{eval$e}
calculate!{$(eval$es),+}
}};
}

fn main(){
calculate!{// Look ma! Variadic `calculate!`!
eval1+2,
eval3+4,
eval(2*3)+1
}
}
Rust is able to interact with C's variadic system via a c_variadic feature switch. As with other C interfaces, the system is considered unsafe to Rust.

Interface with C and C++

Rust has a foreign function interface (FFI) that can be used both to call code written in languages such as C from Rust and to call Rust code from those languages. As of 2023, a external library called CXX exists for calling to or from C++. Rust and C differ in how they lay out structs in memory, so Rust structs may be given a #[repr(C)] attribute, forcing the same layout as the equivalent C struct.

Components

Compiling a Rust program with Cargo

The Rust ecosystem includes its compiler, its standard library, and additional components for software development. Component installation is typically managed by rustup, a Rust toolchain installer developed by the Rust project.

Compiler

The Rust compiler is named rustc. Internally, rustc is a frontend to various backends that are used for further device-specific and platform-specific binary code files (e.g. ELF or WASM binary) generation (compilation). The most mature and most used backend in rustc is the LLVM intermediate representation (bytecode) compiler,[better source needed] but a Cranelift-based backend and a GCC-based backend are also available in nightly builds of the compiler.

Standard library

The Rust standard library defines and implements many widely used custom data types, including core data structures such as Vec, Option, and HashMap, as well as smart pointer types. Rust also provides a way to exclude most of the standard library using the attribute #![no_std]; this enables applications, such as embedded devices, which want to remove dependency code or provide their own core data structures. Internally, the standard library is divided into three parts, core, alloc, and std, where std and alloc are excluded by #![no_std].

Screenshot of crates.io in June 2022

Cargo

Cargo is Rust's build system and package manager. It downloads, compiles, distributes, and uploads packages—called crates—that are maintained in an official registry. It also acts as a front-end for Clippy and other Rust components.

By default, Cargo sources its dependencies from the user-contributed registry crates.io, but Git repositories and crates in the local filesystem, and other external sources can also be specified as dependencies.

Rustfmt

Rustfmt is a code formatter for Rust. It formats whitespace and indentation to produce code in accordance with a common style, unless otherwise specified. It can be invoked as a standalone program, or from a Rust project through Cargo.

Example output of Clippy on a hello world Rust program

Clippy

Clippy is Rust's built-in linting tool to improve the correctness, performance, and readability of Rust code. It was created in 2014[better source needed] and named after Microsoft Office's assistant, an anthropomorphized paperclip of the same name. As of 2024, it has more than 700 rules, which can be browsed online and filtered by category.

Versioning system

Following Rust 1.0, new features are developed in nightly versions which are released daily. During each six-week release cycle, changes to nightly versions are released to beta, while changes from the previous beta version are released to a new stable version.

Every two or three years, a new "edition" is produced. Editions are released to allow making limited breaking changes, such as promoting await to a keyword to support async/await features. Crates targeting different editions can interoperate with each other, so a crate can upgrade to a new edition even if its callers or its dependencies still target older editions. Migration to a new edition can be assisted with automated tooling.

IDE support

The most popular language server for Rust is Rust Analyzer, which officially replaced the original language server, RLS, in July 2022. Rust Analyzer provides IDEs and text editors with information about a Rust project; basic features including autocompletion, and the display of compilation errors while editing.

Performance

In general, Rust's memory safety guarantees do not impose a runtime overhead. A notable exception is array indexing which is checked at runtime, though this often does not impact performance. Since it does not perform garbage collection, Rust is often faster than other memory-safe languages.

Rust provides two "modes": safe and unsafe. Safe mode is the "normal" one, in which most Rust is written. In unsafe mode, the developer is responsible for the code's memory safety, which is useful for cases where the compiler is too restrictive.

Many of Rust's features are so-called zero-cost abstractions, meaning they are optimized away at compile time and incur no runtime penalty. The ownership and borrowing system permits zero-copy implementations for some performance-sensitive tasks, such as parsing. Static dispatch is used by default to eliminate method calls, with the exception of methods called on dynamic trait objects. The compiler also uses inline expansion to eliminate function calls and statically-dispatched method invocations.

Since Rust utilizes LLVM, any performance improvements in LLVM also carry over to Rust. Unlike C and C++, Rust allows for reordering struct and enum elements to reduce the sizes of structures in memory, for better memory alignment, and to improve cache access efficiency.

Adoption

Early homepage of Mozilla's Servo browser engine

Rust has been used in software spanning across different domains. Rust was initially funded by Mozilla as part of developing Servo, an experimental parallel browser engine, in collaboration with Samsung. Components from the Servo engine were later incorporated in the Gecko browser engine underlying Firefox. In January 2023, Google (Alphabet) announced support for third party Rust libraries in Chromium and consequently in the ChromeOS code base.

Rust is used in several backend software projects of large web services. OpenDNS, a DNS resolution service owned by Cisco, uses Rust internally. Amazon Web Services began developing projects in Rust as early as 2017, including Firecracker, a virtualization solution; Bottlerocket, a Linux distribution and containerization solution; and Tokio, an asynchronous networking stack. Microsoft Azure IoT Edge, a platform used to run Azure services on IoT devices, has components implemented in Rust. Microsoft also uses Rust to run containerized modules with WebAssembly and Kubernetes. Cloudflare, a company providing content delivery network services uses Rust for its firewall pattern matching engine.

In operating systems, the Rust for Linux project was begun in 2021 to add Rust support to the Linux kernel. Support for Rust (along with support for C and Assembly language) was officially added in version 6.1. Microsoft announced in 2020 that parts of Microsoft Windows are being rewritten in Rust. As of 2023, DWriteCore, a system library for text layout and glyph render, has about 152,000 lines of Rust code and about 96,000 lines of C++ code, and saw a performance increase of 5 to 15 percent in some cases. Google announced support for Rust in the Android operating system also in 2021. Other operating systems written in Rust include Redox, a "Unix-like" operating system and microkernel, and Theseus, an experimental operating system with modular state management. Rust is also used for command-line tools and operating system components, including stratisd, a file system manager and COSMIC, a desktop environment by System76.

Ruffle, a web emulator for Adobe Flash SWF files

In web development, the npm package manager started using Rust in production in 2019. Deno, a secure runtime for JavaScript and TypeScript, is built with V8, Rust, and Tokio. Other notable adoptions in this space include Ruffle, an open-source SWF emulator, and Polkadot, an open source blockchain and cryptocurrency platform.

Discord, an instant messaging social platform uses Rust for portions of its backend, as well as client-side video encoding. In 2021, Dropbox announced their use of Rust for a screen, video, and image capturing service. Facebook (Meta) used Rust for Mononoke, a server for the Mercurial version control system.

In the 2023 Stack Overflow Developer Survey, 13% of respondents had recently done extensive development in Rust. The survey also named Rust the "most loved programming language" every year from 2016 to 2023 (inclusive), based on the number of developers interested in continuing to work in the same language. In 2023, Rust was the 6th "most wanted technology", with 31% of developers not currently working in Rust expressing an interest in doing so.

Community

A bright orange crab icon
Some Rust users refer to themselves as Rustaceans (a pun on crustacean) and have adopted an orange crab, Ferris, as their unofficial mascot.

Rust Foundation

Rust Foundation
FormationFebruary 8, 2021; 2 years ago (2021-02-08)
Founders
TypeNonprofit organization
Location
Shane Miller
Rebecca Rumbul
Websitefoundation.rust-lang.org

The Rust Foundation is a non-profit membership organization incorporated in United States, with the primary purposes of backing the technical project as a legal entity and helping to manage the trademark and infrastructure assets.

It was established on February 8, 2021, with five founding corporate members (Amazon Web Services, Huawei, Google, Microsoft, and Mozilla). The foundation's board is chaired by Shane Miller. Starting in late 2021, its Executive Director and CEO is Rebecca Rumbul. Prior to this, Ashley Williams was interim executive director.

Governance teams

The Rust project is composed of teams that are responsible for different subareas of the development. The compiler team develops, manages, and optimizes compiler internals; and the language team designs new language features and helps implement them. The Rust project website lists 9 top-level teams as of January 2024. Representatives among teams form the Leadership council, which oversees the Rust project as a whole.

See also


This page was last updated at 2024-02-02 06:45 UTC. Update now. View original page.

All our content comes from Wikipedia and under the Creative Commons Attribution-ShareAlike License.


Top

If mathematical, chemical, physical and other formulas are not displayed correctly on this page, please useFirefox or Safari