HOME

TheInfoList



OR:

Rust is a
multi-paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, su ...
,
general-purpose programming language In computer software, a general-purpose programming language (GPL) is a programming language for building software in a wide variety of application domains. Conversely, a domain-specific programming language is used within a specific area. For ex ...
. Rust emphasizes
performance A performance is an act of staging or presenting a play, concert, or other form of entertainment. It is also defined as the action or process of carrying out or accomplishing an action, task, or function. Management science In the work place ...
,
type safety In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that i ...
, and
concurrency Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
. Rust enforces memory safety—that is, that all
references Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
point to valid memory—without requiring the use of a garbage collector or
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
present in other memory-safe languages. To simultaneously enforce memory safety and prevent concurrent data races, Rust's "borrow checker" tracks the object lifetime of all references in a program during compilation. Rust is popular for systems programming but also offers high-level features including some
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
constructs. Software developer Graydon Hoare created Rust as a personal project while working at
Mozilla Mozilla (stylized as moz://a) is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, spreads and supports Mozilla products, thereby promoting exclusively free software and open standards, w ...
Research in 2006. Mozilla officially sponsored the project in 2009. Since the first stable release in May 2015, Rust has been adopted by companies including
Amazon Amazon most often refers to: * Amazons, a tribe of female warriors in Greek mythology * Amazon rainforest, a rainforest covering most of the Amazon basin * Amazon River, in South America * Amazon (company), an American multinational technolog ...
, Discord,
Dropbox Dropbox is a file hosting service operated by the American company Dropbox, Inc., headquartered in San Francisco, California, U.S. that offers cloud storage, file synchronization, personal cloud, and client software. Dropbox was founded in 2 ...
,
Facebook Facebook is an online social media and social networking service owned by American company Meta Platforms. Founded in 2004 by Mark Zuckerberg with fellow Harvard College students and roommates Eduardo Saverin, Andrew McCollum, Dustin ...
(
Meta Meta (from the Greek μετά, '' meta'', meaning "after" or "beyond") is a prefix meaning "more comprehensive" or "transcending". In modern nomenclature, ''meta''- can also serve as a prefix meaning self-referential, as a field of study or ende ...
),
Google Google LLC () is an American Multinational corporation, multinational technology company focusing on Search Engine, search engine technology, online advertising, cloud computing, software, computer software, quantum computing, e-commerce, ar ...
(
Alphabet An alphabet is a standardized set of basic written graphemes (called letters) that represent the phonemes of certain spoken languages. Not all writing systems represent language in this way; in a syllabary, each character represents a s ...
), and
Microsoft Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation producing Software, computer software, consumer electronics, personal computers, and related services headquartered at th ...
. Rust has been noted for its growth as a newer language and has been the subject of academic programming languages research.


History


Origins (2006–2012)

Rust grew out of a personal project begun in 2006 by
Mozilla Mozilla (stylized as moz://a) is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, spreads and supports Mozilla products, thereby promoting exclusively free software and open standards, w ...
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. The project was officially announced by Mozilla in 2010. During the same year, work had shifted from the initial
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
written in
OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language which extends the Caml dialect of ML with object-oriented features. OCaml was created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, D ...
to a
self-hosting compiler In computer programming, self-hosting is the use of a program as part of the toolchain or operating system that produces new versions of that same program—for example, a compiler that can compile its own source code. Self-hosting software is co ...
based on
LLVM LLVM is a set of compiler and toolchain technologies that can be used to develop a front end for any programming language and a back end for any instruction set architecture. LLVM is designed around a language-independent intermediate repre ...
written in Rust. The new Rust compiler successfully compiled itself in 2011.


Evolution (2012–2019)

Rust's
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
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 Polymorphism, polymorphic, polymorph, polymorphous, or polymorphy may refer to: Computing * Polymorphism (computer science), the ability in programming to present the same programming interface for differing underlying forms * Ad hoc polymorphis ...
through the use of interfaces. In October 2012, version 0.4 was released and added traits as a means for
inheritance Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offici ...
. Interfaces were unified with traits and removed as a separate feature, and classes were replaced by a combination of implementations and structured types. Prior to version 0.4, Rust also supported typestate analysis through
contracts A contract is a legally enforceable agreement between two or more parties that creates, defines, and governs mutual rights and obligations between them. A contract typically involves the transfer of goods, services, money, or a promise to ...
. It was removed in release 0.4, though the same functionality can be achieved by leveraging Rust's type system. 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++ in addition to the languages D, Go, and
Nim Nim is a mathematical two player game. Nim or NIM may also refer to: * Nim (programming language) * Nim Chimpsky, a signing chimpanzee Acronyms * Network Installation Manager, an IBM framework * Nuclear Instrumentation Module * Negative index met ...
(then Nimrod). According to Binstock, while Rust was "widely viewed as a remarkably elegant language", adoption slowed because it repeatedly changed between versions. The first
stable release A stable is a building in which livestock, especially horses, are kept. It most commonly means a building that is divided into separate stalls for individual animals and livestock. There are many different types of stables in use today; the ...
, Rust 1.0, was announced on May 15, 2015.


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 COVID-19 pandemic, also known as the coronavirus pandemic, is an ongoing global pandemic of coronavirus disease 2019 (COVID-19) caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2). The novel virus was first identified ...
. The team behind Servo, a browser engine written in Rust, was completely 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
trademark A trademark (also written trade mark or trade-mark) is a type of intellectual property consisting of a recognizable sign, design, or expression that identifies products or services from a particular source and distinguishes them from oth ...
s and
domain name A domain name is a string that identifies a realm of administrative autonomy, authority or control within the Internet. Domain names are often used to identify services provided through the Internet, such as websites, email services and more. ...
s, and take financial responsibility for their costs. On February 8, 2021, the formation of the
Rust Foundation Rust is a multi-paradigm, general-purpose programming language. Rust emphasizes performance, type safety, and concurrency. Rust enforces memory safety—that is, that all references point to valid memory—without requiring the use of a garb ...
was announced by its five founding companies (
AWS Amazon Web Services, Inc. (AWS) is a subsidiary of Amazon that provides on-demand cloud computing platforms and APIs to individuals, companies, and governments, on a metered pay-as-you-go basis. These cloud computing web services provide di ...
,
Huawei Huawei Technologies Co., Ltd. ( ; ) is a Chinese multinational technology corporation headquartered in Shenzhen, Guangdong, China. It designs, develops, produces and sells telecommunications equipment, consumer electronics and various smart ...
,
Google Google LLC () is an American Multinational corporation, multinational technology company focusing on Search Engine, search engine technology, online advertising, cloud computing, software, computer software, quantum computing, e-commerce, ar ...
,
Microsoft Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation producing Software, computer software, consumer electronics, personal computers, and related services headquartered at th ...
, and Mozilla). In a
blog A blog (a truncation of "weblog") is a discussion or informational website published on the World Wide Web consisting of discrete, often informal diary-style text entries (posts). Posts are typically displayed in reverse chronological order ...
post published on April 6, 2021, Google announced support for Rust within Android Open Source Project as an alternative to C/C++. On November 22, 2021, the Moderation team, responsible for enforcing community standards and the
Code of Conduct A code of conduct is a set of rules outlining the norms, rules, and responsibilities or proper practices of an individual party or an organization. Companies' codes of conduct A company code of conduct is a set of rules which is commonly writt ...
, announced their resignation "in protest of the Core Team placing themselves unaccountable to anyone but themselves." In May 2022, the Rust core team, other leads, and certain members of the Rust Foundation board sent out a statement with governance reforms in response to the incident.


Syntax and semantics


Hello World program

Below is a
"Hello, World!" program A "Hello, World!" program is generally a computer program that ignores any input and outputs or displays a message similar to "Hello, World!". A small piece of code in most general-purpose programming languages, this program is used to illustr ...
in Rust. The keyword is used to denote a function, and the println!
macro Macro (or MACRO) may refer to: Science and technology * Macroscopic, subjects visible to the eye * Macro photography, a type of close-up photography * Image macro, a picture with text superimposed * Monopole, Astrophysics and Cosmic Ray Observat ...
prints the message to standard output.
Statements Statement or statements may refer to: Common uses * Statement (computer science), the smallest standalone element of an imperative programming language *Statement (logic), declarative sentence that is either true or false *Statement, a declarativ ...
in Rust are separated by semicolons. fn main()


Keywords and control flow

In Rust, blocks of code are delimited by curly brackets, and
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
is annotated with keywords such as if, else,
while ''While'' is a word in the English language that functions both as a noun and as a subordinating conjunction. Its meaning varies largely based on its intended function, position in the phrase and even the writer or speaker's regional dialec ...
, and
for For or FOR may refer to: English language *For, a preposition *For, a complementizer *For, a grammatical conjunction Science and technology * Fornax, a constellation * for loop, a programming language statement * Frame of reference, in physic ...
.
Pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
is provided using the keyword. In the examples below, explanations are given in comments, which start with . fn main()


Expression blocks

Despite its syntactic resemblance to C and C++, Rust is more significantly influenced by
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
languages, including
Standard ML Standard ML (SML) is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of ...
,
OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language which extends the Caml dialect of ML with object-oriented features. OCaml was created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, D ...
, Haskell, and Erlang. For example, nearly every part of a function body is an expression, even control flow operators. The ordinary if expression also takes the place of C's ternary conditional. 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 will be used as the
return value In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is s ...
, as seen in the following recursive implementation of the
factorial In mathematics, the factorial of a non-negative denoted is the product of all positive integers less than or equal The factorial also equals the product of n with the next smaller factorial: \begin n! &= n \times (n-1) \times (n-2) ...
function: fn factorial(i: u64) -> u64 The following iterative implementation uses the ..= operator to create an inclusive range: fn factorial(i: u64) -> u64


Types

Rust is strongly typed and
statically typed In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer program ...
: all types of variables must be known during compilation, and assigning a value of a different type to a variable will result in a compilation error. The default integer type is , and the default
floating point In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can be r ...
type is . If the type of a
literal Literal may refer to: * Interpretation of legal concepts: ** Strict constructionism ** The plain meaning rule (a.k.a. "literal rule") * Literal (mathematical logic), certain logical roles taken by propositions * Literal (computer programmin ...
number is not explicitly provided, either it is inferred from the context or the default type is used. Unlike other languages, Rust does not use
null pointer In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object. Programs routinely use null pointers to represent conditions such as the end of a list of unknown lengt ...
s to indicate a lack of data, as doing so can lead to accidental dereferencing. Therefore, in order to uphold its safety guarantees, it is impossible to dereference null pointers unless the code block is manually checked and explicitly declared unsafe through the use of an unsafe block. Rust instead uses an Option type, which has two variants, Some(T) (which indicates that a value is present) and None (analogous to the null pointer). Option implements a "null pointer optimization" avoiding any overhead for types which cannot have a null value (references or the NonZero types, for example). Option values must be handled using syntactic sugar, such as the if let construction, in order to access the inner value (in this case, a string): fn main()


Generics

More advanced features in Rust include the use of
generic function In computer programming, a generic function is a function defined for polymorphism. In statically typed languages In statically typed languages (such as C++ and Java), the term ''generic functions'' refers to a mechanism for ''compile-time pol ...
s to reduce duplicate code. This capability is called
parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
. The following is a Rust program to calculate the sum of two things, for which addition is implemented using a generic function: use std::ops::Add; // sum is a generic function with one type parameter, T fn sum(num1: T, num2: T) -> T where T: Add, // T must implement the Add trait where addition returns another T fn main() At compile-time, polymorphic functions like sum are instantiated with the specific types that are needed by the code (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.


Ownership and lifetimes

Rust's ownership system consists of rules that ensure memory safety without using a garbage collector. In the system, each value in Rust 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 that 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) fn main() ''Lifetimes'' are a usually implicit part of all
reference types In computer programming, data types can be divided into two categories: value types (or by-value types) and reference types (or by-reference types). Value types are completely represented by their meaning, while reference types are references Ref ...
in Rust. Each particular lifetime encompasses a set of locations in the code for which a variable is valid. The borrow checker in the Rust compiler uses lifetimes to ensure that the values pointed to by a reference remain valid. It also ensures that a mutable reference only exists if no immutable references exist at the same time. Rust's memory and ownership system was influenced by
region-based memory management In computer science, region-based memory management is a type of memory management in which each allocated object is assigned to a region. A region, also called a zone, arena, area, or memory context, is a collection of allocated objects that c ...
in languages such as Cyclone and ML Kit. Rust defines the relationship between the lifetimes of the objects used and created by functions as part of their signature using ''lifetime parameters''. When a stack variable or temporary goes out of scope, it is ''dropped'' by running its destructor. The destructor may be programmatically defined through the drop function. This structure enforces the so-called resource acquisition is initialization (RAII) design pattern, in which resources, like 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 needs to 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. use std::collections::HashMap; // This struct has one lifetime parameter, 'src. The name is only used within the struct's definition. # erive(Debug)struct Config<'src> // 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> fn main()


Features

Rust aims to support concurrent systems programming, which has inspired a feature set with an emphasis on safety, control of memory layout, and
concurrency Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
.


Memory safety

Rust is designed to be
memory safe Memory safety is the state of being protected from various software bugs and Vulnerability (computing), security vulnerabilities when dealing with random-access memory, memory access, such as buffer overflows and dangling pointers. For example, J ...
. 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. To replicate pointers being either valid or NULL, such as in linked list or
binary tree In computer science, a binary tree is a k-ary k = 2 tree data structure in which each node has at most two children, which are referred to as the ' and the '. A recursive definition using just set theory notions is that a (non-empty) binar ...
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the rel ...
s, the Rust core library provides an
option type In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions whic ...
, which can be used to test whether a pointer has Some value or None. Rust has added syntax to manage
lifetimes ''LifeTimes'' is an album by Diana Hubbard, released in 1979 by Waterhouse Records 8. In addition to Diana Hubbard, the album includes musical contributions from Chick Corea, Stanley Clarke, John Goodsall, Michael Boddicker, and Patrick Moraz ...
, which are checked at compile time by the ''borrow checker''. Unsafe code can subvert some of these restrictions using the unsafe keyword. Unsafe code may also be used for low-level functionality like volatile memory access, architecture-specific intrinsics,
type punning In computer science, a type punning is any programming technique that subverts or circumvents the type system of a programming language in order to achieve an effect that would be difficult or impossible to achieve within the bounds of the formal ...
, and inline assembly.


Memory management

Rust does not use automated garbage collection. Memory and other resources are managed through the "resource acquisition is initialization" convention, with optional
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
. 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 In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavio ...
. Rust's type system separates shared,
immutable In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
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.


Types and polymorphism

Rust's type system supports a mechanism called traits, inspired by
type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T a ...
es in the Haskell language, to define shared behavior between different types. For example, floats and integers both implement the Add trait because they can both be added; and any type that can be converted to a string implements the Display or Debug traits. This facility is known as ad hoc polymorphism. Rust uses type inference for variables declared with the keyword let. Such variables do not require a value to be initially assigned to determine their type. A compile time error results if any branch of code leaves the variable without an assignment. Variables assigned multiple times must be marked with the keyword mut (short for mutable). A function can be given generic
parameters A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
, which allows the same function to be applied to different types. 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 Rust 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 in Rust 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 Rust, user-defined types are created with the struct or enum keywords. The struct keyword is used to denote a
record type Record type is a family of typefaces designed to allow medieval manuscripts (specifically those from England) to be published as near-facsimiles of the originals. The typefaces include many special characters intended to replicate the various s ...
that groups multiple related values. enums can take on different variants in runtime, with its capabilities similiar to algebraic data types found in functional programming languages. Both structs and enums can contain fields with different types. The impl keyword can define methods for the types (data and functions are defined separately) or implement a trait for the types. Traits are used to restrict generic parameters and because traits can provide a type with more methods than the user defined. For example, the trait Iterator requires that the next method be defined for the type. Once the next method is defined the trait provides common functional helper methods over the iterator like map or filter. Type aliases, including generic arguments, can also be defined with the type keyword. The type system within Rust is based around implementations, traits and structured types. Implementations fulfill a role similar to that of classes within other languages and are defined with the keyword impl. Traits provide inheritance and polymorphism; they allow methods to be defined and mixed in to implementations. Structured types are used to define fields. Implementations and traits cannot define fields themselves, and only traits can provide inheritance. Among other benefits, this prevents the
diamond problem Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
of
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object o ...
, as in C++. In other words, Rust supports interface inheritance but replaces implementation inheritance with composition; see
composition over inheritance Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes tha ...
. Rust uses
linear types Substructural type systems are a family of type systems analogous to substructural logics where one or more of the structural rules are absent or only allowed under controlled circumstances. Such systems are useful for constraining access to sy ...
, where each value is used exactly once, to enforce
type safety In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that i ...
. This enables
software fault isolation In computer security, a sandbox is a security mechanism for separating running programs, usually in an effort to mitigate system failures and/or software vulnerabilities from spreading. The isolation metaphor is taken from the idea of children w ...
with a low overhead.


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 Duck typing in computer programming is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an object can be used for a particular purpose. With nominative t ...
). Dynamically dispatched trait objects are declared using the syntax Box where Tr is a trait. For example, it is possible to create a list of objects which each can be printed out as follows: let v: Vec> = vec! ox::new(3), Box::new(5.0), Box::new("hi")/code>. Trait objects are dynamically sized; however, prior to the 2018 edition, the dyn keyword was optional. A trait object is essentially a fat pointer that include a pointer as well as additional information about what type the pointer is.


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 use Rust functions that are compiled before other components to run and modify the compiler's input
token Token may refer to: Arts, entertainment, and media * Token, a game piece or counter, used in some games * The Tokens, a vocal music group * Tolkien Black, a recurring character on the animated television series ''South Park,'' formerly known as ...
stream. 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 # erive(CustomDerive)/code> * Attribute macros # ustom_attribute/code> The println! macro is an example of a function-like macro and serde_derive is a commonly used library for generating code for reading and writing data in many formats such as
JSON JSON (JavaScript Object Notation, pronounced ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other s ...
. 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 derive procedural macros to implement JSON reading and writing as well as the ability to format a structure for debugging. use serde_json::; # erive(Serialize, Deserialize, Debug)struct Point fn main()


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. Rust also has a library, CXX, 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 #
epr(C) EPR may refer to: Science and technology * EPR (nuclear reactor), European Pressurised-Water Reactor * EPR paradox (Einstein–Podolsky–Rosen paradox), in physics * Earth potential rise, in electrical engineering * East Pacific Rise, a mid-ocean ...
/code> attribute, forcing the same layout as the equivalent C struct.


Components

Besides the compiler and standard library, the Rust ecosystem includes additional components for software development. Component installation is typically managed by , a Rust
toolchain In software, a toolchain is a set of programming tools that is used to perform a complex software development task or to create a software product, which is typically another computer program or a set of related programs. In general, the tools for ...
installer developed by the Rust project.


Standard library

The Rust standard library is split into three crates: , , and . When a project is annotated with the crate-level attribute , the crate is excluded.


Cargo

Cargo is Rust's build system and
package manager A package manager or package-management system is a collection of software tools that automates the process of installing, upgrading, configuring, and removing computer programs for a computer in a consistent manner. A package manager deals w ...
. Cargo downloads, compiles, distributes, and uploads packages, called ''crates'', maintained in the official registry. Cargo 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 be specified as dependencies, too.


Rustfmt

Rustfmt is a code formatter for Rust. It takes Rust source code as input and changes the whitespace and indentation to produce code formatted in accordance to a common
style Style is a manner of doing or presenting things and may refer to: * Architectural style, the features that make a building or structure historically identifiable * Design, the process of creating something * Fashion, a prevailing mode of clothing ...
unless specified otherwise. Rustfmt can be invoked as a standalone program or on a Rust project through Cargo.


Clippy

Clippy is Rust's built-in linting tool to improve the correctness, performance, and readability of Rust code. It was created in 2014 and named after the eponymous Microsoft Office feature. As of 2021, Clippy has more than 450 rules, which can be browsed online and filtered by category.


Versioning system

Following Rust 1.0, new features are developed in ''nightly'' versions which release on a daily basis. During each release cycle of six weeks, changes on nightly versions are released to beta, while changes from the previous beta version are released to a new stable version. Every three years, a new "edition" is produced. Editions are released to provide an easy reference point for changes due to the frequent nature of Rust's ''train release schedule,'' and to provide a window to make limited breaking changes. Editions are largely compatible and migration to a new edition is assisted with automated tooling.


IDE support

The most popular language server for Rust is ''rust-analyzer''. The original language server, ''RLS'' was officially deprecated in favor of ''rust-analyzer'' in July 2022. These projects provide IDEs and
text editor A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be u ...
s with more information about a Rust project, with basic features including autocompletion, and display of compilation errors while editing.


Performance

Rust aims "to be as efficient and portable as idiomatic C++, without sacrificing safety". Rust does not perform garbage collection, which allows it to be more efficient and performant than other memory-safe languages. Rust provides two "modes": safe and unsafe. The safe mode is the "normal" one, in which most Rust is written. In unsafe mode, the developer is responsible for the correctness of the code, making it possible to create applications which require low-level features. It has been demonstrated empirically that unsafe Rust is not always more performant than safe Rust, and can even be slower in some cases. 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 "Zero-copy" describes computer operations in which the CPU does not perform the task of copying data from one memory area to another or in which unnecessary data copies are avoided. This is frequently used to save CPU cycles and memory bandwid ...
implementations for some performance-sensitive tasks, such as
parsing Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. The term ''parsing'' comes from Lati ...
. Static dispatch is used by default to eliminate
method call A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s, with the exception of methods called on dynamic trait objects. The compiler also uses
inline expansion In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the called function. Inline expansion is similar to macro expansion, but occurs during compilation, without ch ...
to eliminate function calls and statically dispatched method invocations entirely. Since Rust utilizes LLVM, any performance improvements in LLVM also carry over to Rust. Unlike C and C++, Rust allows re-organizing struct and enum element ordering. This can be done to reduce the size of structures in memory, for better memory alignment, and to improve cache access efficiency.


Adoption

According to the
Stack Overflow In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many facto ...
Developer Survey in 2022, 9% of respondents have recently done extensive development in Rust. The survey has additionally named Rust the "most loved programming language" every year from 2016 to 2022 (inclusive), a ranking based on the number of current developers who express an interest in continuing to work in the same language. In 2022, Rust tied with Python for "most wanted technology" with 18% of developers not currently working in Rust expressing an interest in doing so. Rust has been adopted for components at a number of major software companies, including
Amazon Amazon most often refers to: * Amazons, a tribe of female warriors in Greek mythology * Amazon rainforest, a rainforest covering most of the Amazon basin * Amazon River, in South America * Amazon (company), an American multinational technolog ...
, Discord,
Dropbox Dropbox is a file hosting service operated by the American company Dropbox, Inc., headquartered in San Francisco, California, U.S. that offers cloud storage, file synchronization, personal cloud, and client software. Dropbox was founded in 2 ...
,
Facebook Facebook is an online social media and social networking service owned by American company Meta Platforms. Founded in 2004 by Mark Zuckerberg with fellow Harvard College students and roommates Eduardo Saverin, Andrew McCollum, Dustin ...
(
Meta Meta (from the Greek μετά, '' meta'', meaning "after" or "beyond") is a prefix meaning "more comprehensive" or "transcending". In modern nomenclature, ''meta''- can also serve as a prefix meaning self-referential, as a field of study or ende ...
), Google (
Alphabet An alphabet is a standardized set of basic written graphemes (called letters) that represent the phonemes of certain spoken languages. Not all writing systems represent language in this way; in a syllabary, each character represents a s ...
), and Microsoft.


Web browsers and services

*
Firefox Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements current and ...
has two projects written in Rust: the Servo parallel
browser engine A browser engine (also known as a layout engine or rendering engine) is a core software component of every major web browser. The primary job of a browser engine is to transform HTML documents and other resources of a web page into an interactiv ...
developed by Mozilla in collaboration with
Samsung The Samsung Group (or simply Samsung) ( ko, 삼성 ) is a South Korean multinational manufacturing conglomerate headquartered in Samsung Town, Seoul, South Korea. It comprises numerous affiliated businesses, most of them united under the ...
; and Quantum, which is composed of several sub-projects for improving Mozilla's
Gecko Geckos are small, mostly carnivorous lizards that have a wide distribution, found on every continent except Antarctica. Belonging to the infraorder Gekkota, geckos are found in warm climates throughout the world. They range from . Geckos ar ...
browser engine. *
OpenDNS OpenDNS is an American company providing Domain Name System (DNS) resolution services—with features such as phishing protection, optional content filtering, and DNS lookup in its DNS servers—and a cloud computing security product suite, Umbr ...
uses Rust in some of its internal projects. * Deno, a secure runtime for
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
and
TypeScript TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large appl ...
, is built with V8, Rust, and
Tokio Tokio may refer to: * , the capital of Japan, used primarily in non-English-speaking countries may also refer to: Music * Tokio (band), a Japanese pop/rock band ** ''Tokio'' (album), their debut album * Tokio Hotel, a German rock band * Toki ...
. *
Amazon Web Services Amazon Web Services, Inc. (AWS) is a subsidiary of Amazon.com, Amazon that provides Software as a service, on-demand cloud computing computing platform, platforms and Application programming interface, APIs to individuals, companies, and gover ...
has multiple projects written in Rust, including
Firecracker A firecracker (cracker, noise maker, banger) is a small explosive device primarily designed to produce a large amount of noise, especially in the form of a loud bang, usually for celebration or entertainment; any visual effect is incidental to ...
, a virtualization solution, and Bottlerocket, a
Linux distribution A Linux distribution (often abbreviated as distro) is an operating system made from a software collection that includes the Linux kernel and, often, a package management system. Linux users usually obtain their operating system by downloading on ...
and
containerization Containerization is a system of intermodal freight transport using intermodal containers (also called shipping containers and ISO containers). Containerization is also referred as "Container Stuffing" or "Container Loading", which is the p ...
solution. *
Cloudflare Cloudflare, Inc. is an American content delivery network and DDoS mitigation company, founded in 2009. It primarily acts as a reverse proxy between a website's visitor and the Cloudflare customer's hosting provider. Its headquarters are in San ...
's implementations of the
QUIC QUIC (pronounced "quick") is a general-purpose transport layer network protocol initially designed by Jim Roskind at Google, implemented, and deployed in 2012, announced publicly in 2013 as experimentation broadened, and described at an IETF meet ...
protocol and firewall rules are written in Rust. * Arti is a Rust implementation of Tor server by
The Tor Project The Tor Project, Inc. is a Seattle-based 501(c)(3) research-education nonprofit organization founded by computer scientists Roger Dingledine, Nick Mathewson and five others. The Tor Project is primarily responsible for maintaining software for ...
.


Operating systems

*
Redox Redox (reduction–oxidation, , ) is a type of chemical reaction in which the oxidation states of substrate (chemistry), substrate change. Oxidation is the loss of Electron, electrons or an increase in the oxidation state, while reduction ...
is a "full-blown Unix-like operating system" including a
microkernel In computer science, a microkernel (often abbreviated as μ-kernel) is the near-minimum amount of software that can provide the mechanisms needed to implement an operating system (OS). These mechanisms include low-level address space management, ...
written in Rust. * Theseus, an experimental operating system described as having "intralingual design": leveraging Rust's programming language mechanisms for implementing the OS. * The Google
Fuchsia ''Fuchsia'' () is a genus of flowering plants that consists mostly of shrubs or small trees. The first to be scientifically described, ''Fuchsia triphylla'', was discovered on the Caribbean island of Hispaniola (Haiti and the Dominican Republic ...
capability-based security Capability-based security is a concept in the design of secure computing systems, one of the existing security models. A capability (known in some systems as a key) is a communicable, unforgeable token of authority. It refers to a value that refe ...
operating system has components written in Rust, including a
TCP/IP The Internet protocol suite, commonly known as TCP/IP, is a framework for organizing the set of communication protocols used in the Internet and similar computer networks according to functional criteria. The foundational protocols in the suit ...
library. * Stratis is a
file system In computing, file system or filesystem (often abbreviated to fs) is a method and data structure that the operating system uses to control how data is stored and retrieved. Without a file system, data placed in a storage medium would be one lar ...
manager written in Rust for
Fedora A fedora () is a hat with a soft brim and indented crown.Kilgour, Ruth Edwards (1958). ''A Pageant of Hats Ancient and Modern''. R. M. McBride Company. It is typically creased lengthwise down the crown and "pinched" near the front on both sides ...
and
RHEL Red Hat Enterprise Linux (RHEL) is a commercial open-source Linux distribution developed by Red Hat for the commercial market. Red Hat Enterprise Linux is released in server versions for x86-64, Power ISA, ARM64, and IBM Z and a desktop vers ...
. * is a Unix/Linux command line alternative to written in Rust. * Rust for Linux is a patch series begun in 2021 to add Rust support to the Linux kernel. * LynxOS-178 and LynxElement unikernel support Rust in their certified toolchain, as of late 2022.


Other notable projects and platforms

* Discord uses Rust for portions of its backend, as well as client-side video encoding, to augment the core infrastructure written in
Elixir ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
. * Microsoft Azure IoT Edge, a platform used to run Azure services and artificial intelligence on IoT devices, has components implemented in Rust. *
Polkadot Red polka dots on a yellow background Girl wearing polka dot dress Polish ceramics German ceramics Polka dot is a pattern consisting of an array of large filled circles of the same size. Polka dots are commonly seen on children's clothing ...
is an open source
blockchain A blockchain is a type of distributed ledger technology (DLT) that consists of growing lists of records, called ''blocks'', that are securely linked together using cryptography. Each block contains a cryptographic hash of the previous block, ...
platform and
cryptocurrency A cryptocurrency, crypto-currency, or crypto is a digital currency designed to work as a medium of exchange through a computer network that is not reliant on any central authority, such as a government or bank, to uphold or maintain it. It ...
written in Rust. * Ruffle is an open-source
SWF SWF ( ) is an Adobe Flash file format used for multimedia, vector graphics and ActionScript.Open Screen Pr ...
emulator written in Rust. * TerminusDB, an open source
graph database A graph database (GDB) is a database that uses graph structures for semantic queries with nodes, edges, and properties to represent and store data. A key concept of the system is the ''graph'' (or ''edge'' or ''relationship''). The graph relat ...
designed for collaboratively building and curating
knowledge graph The Google Knowledge Graph is a knowledge base from which Google serves relevant information in an infobox beside its search results. This allows the user to see the answer in a glance. The data is generated automatically from a variety of so ...
s, is written in
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily a ...
and Rust.


Community


Conferences

Rust's official website lists online forums, messaging platforms, and in-person meetups for the Rust community. Conferences dedicated to Rust development include: * RustConf: an annual conference in
Portland, Oregon Portland (, ) is a port city in the Pacific Northwest and the largest city in the U.S. state of Oregon. Situated at the confluence of the Willamette and Columbia rivers, Portland is the county seat of Multnomah County, the most populou ...
. Held annually since 2016 (except in 2020 and 2021 because of the
COVID-19 pandemic The COVID-19 pandemic, also known as the coronavirus pandemic, is an ongoing global pandemic of coronavirus disease 2019 (COVID-19) caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2). The novel virus was first identified ...
). * Rust Belt Rust: a #rustlang conference in the
Rust Belt The Rust Belt is a region of the United States that experienced industrial decline starting in the 1950s. The U.S. manufacturing sector as a percentage of the U.S. GDP peaked in 1953 and has been in decline since, impacting certain regions a ...
* RustFest: Europe's @rustlang conference * RustCon Asia * Rust LATAM * Oxidize Global


Rust Foundation

The Rust Foundation is a
non-profit A nonprofit organization (NPO) or non-profit organisation, also known as a non-business entity, not-for-profit organization, or nonprofit institution, is a legal entity organized and operated for a collective, public or social benefit, in co ...
membership organization incorporated in
United States The United States of America (U.S.A. or USA), commonly known as the United States (U.S. or US) or America, is a country primarily located in North America. It consists of 50 U.S. state, states, a Washington, D.C., federal district, five ma ...
, with the primary purposes of backing the technical project as a
legal entity In law, a legal person is any person or 'thing' (less ambiguously, any legal entity) that can do the things a human person is usually able to do in law – such as enter into contracts, sue and be sued, own property, and so on. The reason fo ...
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. For example, the Core team is responsible for "managing the overall direction of Rust, subteam leadership, and any cross-cutting issues," the Compiler team is responsible for "developing and managing compiler internals and optimizations," and the Language team is responsible for "designing and helping to implement new language features," according to the official website.


See also

* Comparison of programming languages * History of programming languages *
List of programming languages This is an index to notable programming languages, in current or historical use. Dialects of BASIC, esoteric programming languages, and markup languages are not included. A programming language does not need to be imperative or Turing-complete, ...
* List of programming languages by type


Notes


References


Book sources

*


Others


Further reading

*


External links

* {{Authority control 2010 software Articles with example code Concurrent programming languages Free compilers and interpreters Free software projects Functional languages High-level programming languages Mozilla Multi-paradigm programming languages Pattern matching programming languages Procedural programming languages Programming languages created in 2010 Software using the Apache license Software using the MIT license Statically typed programming languages Systems programming languages