Content deleted Content added
→In academic research: e per sources |
Lead. |
||
(47 intermediate revisions by 18 users not shown) | |||
Line 68:
}}
'''Rust''' is a [[General-purpose programming language|general-purpose]] [[programming language]]. It is noted
Rust supports multiple [[programming paradigm]]s. It was influenced by ideas from [[functional programming]], including [[Immutable object|immutability]], [[higher-order function]]s, [[algebraic data type]]s, and [[pattern matching]]. It also supports [[object-oriented programming]] via structs, [[Union type|enums]], traits, and methods. Rust is noted for enforcing memory safety (i.e., that all [[Reference (computer science)|references]] point to valid memory) without a conventional [[Garbage collection (computer science)|garbage collector]]; instead, memory safety errors and [[data race]]s are prevented by the "borrow checker", which tracks the [[object lifetime]] of references [[Compiler|at compile time]].
Software developer Graydon Hoare created Rust
Rust has been noted for its adoption in many software projects, especially [[web services]] and [[system software]], and is the first language other than [[C (programming language)|C]] and [[Assembly language|assembly]] to be supported in the development of the [[Linux kernel]]. It has been studied academically and has a growing community of developers.
==Etymology==
Rust was named for the [[Rust (fungus)|group of fungi]] that are "over-engineered for survival".<ref name="MITTechReview"/>
The Rust logo was developed in 2011 based on a bicycle [[Crankset#Chainring|chainring]].<ref>{{cite web |title=Rust logo |url=https://bugzilla.mozilla.org/show_bug.cgi?id=680521 |website=[[Bugzilla]] |access-date=2 February 2024 |archive-date=2024-02-02 |archive-url=https://web.archive.org/web/20240202045212/https://bugzilla.mozilla.org/show_bug.cgi?id=680521 |url-status=live }}</ref>
== History ==
=== 2006–2009: Early years ===
[[File:MozillaCaliforniaHeadquarters.JPG|thumb|right|Mozilla Foundation headquarters, 650 Castro Street in [[Mountain View, California]], June 2009]]
Rust began as a personal project by [[Mozilla]] employee Graydon Hoare in 2006.<ref name="MITTechReview">{{cite web |url=https://www.technologyreview.com/2023/02/14/1067869/rust-worlds-fastest-growing-programming-language/ |title=How Rust went from a side project to the world's most-loved programming language |last=Thompson |first=Clive |date=2023-02-14 |website=MIT Technology Review |language=en |access-date=2023-02-23 |archive-date=2024-09-19 |archive-url=https://web.archive.org/web/20240919102849/https://www.technologyreview.com/2023/02/14/1067869/rust-worlds-fastest-growing-programming-language/ |url-status=live }}</ref> Hoare started the project due to his frustration with a broken elevator in his apartment building.<ref name="MITTechReview"/>
During the early years, the Rust [[compiler]] was written in about 38,000 lines of [[OCaml]].<ref name=Klabnik2016ACMHistory/>{{rp|at=15:34}}<ref name=OCamlCompiler>{{Cite web |last=Hoare |first=Graydon |title=Rust Prehistory (Archive of the original Rust OCaml compiler source code) |website=[[GitHub]] |date=November 2016 |url=https://github.com/graydon/rust-prehistory/tree/master |access-date=2024-10-29 }}</ref> Early Rust contained features such as explicit [[object-oriented programming]] via an {{code|obj}} keyword (later removed),<ref name=Klabnik2016ACMHistory/>{{rp|at=10:08}} and a [[typestate analysis|typestates]] system that would allow variables of a type to be tracked along with state changes (such as going from uninitialized to initialized, also removed).<ref name=Klabnik2016ACMHistory/>{{rp|at=13:12}}
=== 2009–2012: Mozilla sponsorship ===
Mozilla officially sponsored the Rust project in 2009.<ref name="MITTechReview"/> [[Brendan Eich]] and other executives, intrigued by the possibility of using Rust for a safe [[web browser]] [[browser engine|engine]], placed engineers on the project including Patrick Walton, Niko Matsakis, Felix Klock, and Manish Goregaokar.<ref name="MITTechReview"/> A conference room taken by the project developers was dubbed "the nerd cave," with a sign placed outside the door.<ref name="MITTechReview"/>
During this time period, work had shifted from the initial OCaml compiler to a [[Self-hosting (compilers)|self-hosting compiler]], ''i.e.'', written in Rust, based on [[LLVM]].<ref name=Rust0.1>{{Cite web |title=0.1 first supported public release Milestone · rust-lang/rust |url=https://github.com/rust-lang/rust/milestone/3?closed=1 |access-date=2024-10-29 |website=[[GitHub]] |language=en}}</ref>{{refn|group=note|The list of Rust compiler versions (referred to as a bootstrapping chain) has history going back to 2012.<ref name=Nelson2022RustConf>{{Cite AV media |url=https://www.youtube.com/watch?v=oUIjG-y4zaA |last=Nelson |first=Jynn |title=RustConf 2022 - Bootstrapping: The once and future compiler |publisher=Rust Team |date=2022-08-05 |access-date=2024-10-29 |___location=Portland, Oregon |via=YouTube}}</ref>}} The Rust ownership system was also in place by 2010.<ref name="MITTechReview"/>
The first public release, Rust 0.1 was released on January 20, 2012<ref name=Rust0.1a>{{Cite mailing list |last=Anderson |first=Brian |date=2012-01-24 |title=[rust-dev] The Rust compiler 0.1 is unleashed |url=https://mail.mozilla.org/pipermail/rust-dev/2012-January/001256.html |mailing-list=rust-dev |access-date=2025-01-07 |archive-url=https://web.archive.org/web/20120124160628/https://mail.mozilla.org/pipermail/rust-dev/2012-January/001256.html |archive-date=January 24, 2012 }}</ref> for Windows, Linux, and MacOS.<ref name=ExtremeTechRust0.1>{{Cite web |last=Anthony |first=Sebastian |date=2012-01-24 |title=Mozilla releases Rust 0.1, the language that will eventually usurp Firefox's C++ |url=https://www.extremetech.com/internet/115207-mozilla-releases-rust-0-1-the-language-that-will-eventually-usurp-firefoxs-c |access-date=2025-01-07 |website=ExtremeTech |language=en}}</ref> The early 2010s saw increasing involvement from open source volunteers outside of Mozilla and outside of the United States. At Mozilla, executives would eventually employ over a dozen engineers to work on Rust full time over the next decade.<ref name="MITTechReview"/>
Line 94 ⟶ 97:
The years from 2012 to 2015 were marked by substantial changes to the Rust [[type system]], especially, removal of the typestate system, consolidation of other language features, and the removal of the [[Garbage collection (computer science)|garbage collector]].<ref name=Klabnik2016ACMHistory/>{{rp|at=18:36}}<ref name="MITTechReview"/> Memory management through the ownership system was gradually consolidated and expanded to prevent memory-related bugs. By 2013, the garbage collector feature was rarely used, and was removed by the team in favor of the ownership system.<ref name="MITTechReview"/> Other changes during this time included the removal of [[pure function]]s, which were declared by an explicit {{code|pure}} annotation, in March 2013.<ref>{{Cite web |title=Purity by pcwalton · Pull Request #5412 · rust-lang/rust |url=https://github.com/rust-lang/rust/pull/5412 |access-date=2024-10-29 |website=[[GitHub]] |language=en}}</ref> Specialized syntax support for [[channel (programming)|channels]] and various pointer types were removed to simplify the language.<ref name=Klabnik2016ACMHistory/>{{rp|at=22:32}}
According to Rust
Graydon Hoare stepped down from Rust in 2013.<ref name="MITTechReview"/>
According to Andrew Binstock writing for ''[[Dr. Dobb's Journal]]'' in January 2014, while Rust was "widely viewed as a remarkably elegant language", adoption slowed because it radically changed from version to version.<ref>{{cite news |last=Binstock |first=Andrew |date=January 7, 2014 |title=The Rise And Fall of Languages in 2013 |website=[[Dr. Dobb's Journal]] |url=https://www.drdobbs.com/jvm/the-rise-and-fall-of-languages-in-2013/240165192 |url-status=dead |archive-url=https://web.archive.org/web/20160807075745/http://www.drdobbs.com/jvm/the-rise-and-fall-of-languages-in-2013/240165192 |archive-date=2016-08-07 |access-date=2022-11-20}}</ref> Rust development at this time was focused on finalizing the language features and moving towards 1.0 so it could begin promising [[backward compatibility]].<ref name=Klabnik2016ACMHistory/>{{rp|at=41:26}}
Line 108 ⟶ 111:
The development of the [[Servo (software)|Servo browser engine]] continued in parallel with Rust, jointly funded by Mozilla and [[Samsung]].<ref>{{cite news|last=Lardinois|first=Frederic|date=2015-04-03|title=Mozilla And Samsung Team Up To Develop Servo, Mozilla's Next-Gen Browser Engine For Multicore Processors|work=[[TechCrunch]]|url=https://techcrunch.com/2013/04/03/mozilla-and-samsung-collaborate-on-servo-mozillas-next-gen-browser-engine-for-tomorrows-multicore-processors/|access-date=2017-06-25|archive-date=2016-09-10|archive-url=https://web.archive.org/web/20160910211537/https://techcrunch.com/2013/04/03/mozilla-and-samsung-collaborate-on-servo-mozillas-next-gen-browser-engine-for-tomorrows-multicore-processors/|url-status=live}}</ref> The teams behind the two projects worked in close collaboration; new features in Rust were tested out by the Servo team, and new features in Servo were used to give feedback back to the Rust team.<ref name=Klabnik2016ACMHistory/>{{rp|at=5:41}} The first version of Servo was released in 2016.<ref name="MITTechReview"/> The [[Firefox]] web browser shipped with Rust code as of 2016 (version 45),<ref name=Klabnik2016ACMHistory/>{{rp|at=53:30}}<ref>{{Cite web |title=Firefox 45.0, See All New Features, Updates and Fixes |url=https://www.mozilla.org/en-US/firefox/45.0/releasenotes/ |access-date=2024-10-31 |website=Mozilla |language=en |archive-date=2016-03-17 |archive-url=https://web.archive.org/web/20160317215950/https://www.mozilla.org/en-US/firefox/45.0/releasenotes/ |url-status=live }}</ref> but components of Servo did not appear in Firefox until September 2017 (version 57) as part of the [[Gecko (software)|Gecko]] and [[Gecko (software)#Quantum|Quantum]] projects.<ref>{{Cite web |last=Lardinois |first=Frederic |date=2017-09-29 |title=It's time to give Firefox another chance |url=https://techcrunch.com/2017/09/29/its-time-to-give-firefox-another-chance/ |access-date=2023-08-15 |website=[[TechCrunch]] |language=en-US |archive-date=2023-08-15 |archive-url=https://web.archive.org/web/20230815025149/https://techcrunch.com/2017/09/29/its-time-to-give-firefox-another-chance/ |url-status=live }}</ref>
Improvements were made to the Rust toolchain ecosystem during the years following 1.0 including [[#Rustfmt|Rustfmt]], [[integrated development environment]] integration,<ref name=Klabnik2016ACMHistory/>{{rp|at=44:56}} and a regular compiler testing and release cycle
The earliest known adoption outside of Mozilla was by individual projects at Samsung, [[Facebook]] (now [[Meta Platforms]]), [[Dropbox]], and others including Tilde, Inc. (the company behind [[ember.js]]).<ref name=Klabnik2016ACMHistory/>{{rp|at=55:44}}<ref name="MITTechReview"/> [[Amazon Web Services]] followed in 2020.<ref name="MITTechReview"/> Engineers acknowledged the risks of adopting a new technology; they cited performance, lack of a garbage collector, safety, and pleasantness of working in the language as reasons for the adoption
=== 2020–present: Mozilla layoffs and Rust Foundation ===
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]].<ref>{{cite web |url=https://www.zdnet.com/article/mozilla-lays-off-250-employees-while-it-refocuses-on-commercial-products/ |title=Mozilla lays off 250 employees while it refocuses on commercial products |last=Cimpanu |first=Catalin |website=[[ZDNET]] |access-date=2020-12-02 |date=2020-08-11 |archive-date=March 18, 2022 |archive-url=https://web.archive.org/web/20220318025804/https://www.zdnet.com/article/mozilla-lays-off-250-employees-while-it-refocuses-on-commercial-products/ |url-status=live}}</ref><ref>{{cite web |url=https://www.engadget.com/mozilla-firefox-250-employees-layoffs-151324924.html |title=Mozilla lays off 250 employees due to the pandemic |website=[[Engadget]] |last=Cooper |first=Daniel |access-date=2020-12-02 |date=2020-08-11 |archive-date=2020-12-13 |archive-url=https://web.archive.org/web/20201213020220/https://www.engadget.com/mozilla-firefox-250-employees-layoffs-151324924.html |url-status=live}}</ref> The team behind Servo was disbanded. The event raised concerns about the future of Rust
On February 8, 2021, the formation of the [[#Rust Foundation|Rust Foundation]] was announced by five founding companies: [[Amazon Web Services]], [[Google]], [[Huawei]], [[Microsoft]], and [[Mozilla]].<ref>{{Cite web |date=2020-02-08 |title=Hello World! |url=https://foundation.rust-lang.org/news/2021-02-08-hello-world/ |access-date=2022-06-04 |website=Rust Foundation |language=en |archive-date=April 19, 2022 |archive-url=https://web.archive.org/web/20220419124635/https://foundation.rust-lang.org/news/2021-02-08-hello-world/ |url-status=live}}</ref><ref>{{Cite web|date=2021-02-09|title=Mozilla Welcomes the Rust Foundation |website=Mozilla Blog |url=https://blog.mozilla.org/blog/2021/02/08/mozilla-welcomes-the-rust-foundation |archive-url=https://web.archive.org/web/20210208212031/https://blog.mozilla.org/blog/2021/02/08/mozilla-welcomes-the-rust-foundation/|archive-date=2021-02-08|access-date=2021-02-09|url-status=live}}</ref> The foundation, led by Shane Miller for its first two years, offered $20,000 grants and other support for programmers working on major Rust features.<ref name="MITTechReview"/> 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++.<ref>{{Cite web|last=Amadeo|first=Ron|date=2021-04-07 |title=Google is now writing low-level Android code in Rust |url=https://arstechnica.com/gadgets/2021/04/google-is-now-writing-low-level-android-code-in-rust/ |access-date=2021-04-08|website=Ars Technica|language=en-us|archive-date=2021-04-08|archive-url=https://web.archive.org/web/20210408001446/https://arstechnica.com/gadgets/2021/04/google-is-now-writing-low-level-android-code-in-rust/|url-status=live}}</ref>
On November 22, 2021, the Moderation Team, which was responsible for enforcing the community code of conduct, announced their resignation "in protest of the Core Team placing themselves unaccountable to anyone but themselves".<ref name="moderation">{{Cite news |first=Tim |last=Anderson |title=Entire Rust moderation team resigns |url=https://www.theregister.com/2021/11/23/rust_moderation_team_quits/ |date=2021-11-23 |access-date=2022-08-04 |website=[[The Register]] |language=en |archive-date=2022-07-14 |archive-url=https://web.archive.org/web/20220714093245/https://www.theregister.com/2021/11/23/rust_moderation_team_quits/ |url-status=live }}</ref> In May 2022, the Rust Core Team, other lead programmers, and
The Rust Foundation posted a draft for a new trademark policy on April 6, 2023
On February 26, 2024, the U.S. [[White House]]
== Syntax and features ==
Line 137 ⟶ 140:
=== Variables ===
[[Variable (computer science)|Variables]] in Rust are defined through the {{rust|let}} keyword.{{sfn|Klabnik|Nichols|2023|p=32}} The example below assigns a value to the variable with name {{
<syntaxhighlight lang="rust">
Line 146 ⟶ 149:
</syntaxhighlight>
Variables are [[Immutable object|immutable]] by default, but adding the {{rust|mut}} keyword allows the variable to be mutated.{{sfn|Klabnik|Nichols|2023|pp=32-33}} The following example uses {{
<syntaxhighlight lang="rust">
Line 158 ⟶ 161:
</syntaxhighlight>
Multiple {{
<syntaxhighlight lang="rust">
Line 202 ⟶ 205:
</syntaxhighlight>
==== {{
An {{rust|if}} [[conditional expression]] executes code based on whether the given value is {{
<syntaxhighlight lang="rust">
Line 233 ⟶ 236:
</syntaxhighlight>
==== {{
<code>[[While loop|while]]</code> can be used to repeat a block of code while a condition is met.{{sfn|Klabnik|Nichols|2023|p=56}}
Line 247 ⟶ 250:
</syntaxhighlight>
==== {{
[[For loop]]s in Rust loop over elements of a collection.{{sfn|Klabnik|Nichols|2023|pp=57-58}}
Line 267 ⟶ 270:
<syntaxhighlight lang="rust">
(1..=100).filter(|&x: i8| -> bool { x % 3 == 0 }).sum()
</syntaxhighlight>
==== {{
More generally, the {{rust|loop}} keyword allows repeating a portion of code until a {{rust|break}} occurs. {{rust|break}} may optionally exit the loop with a value. In the case of nested loops, labels denoted by {{rust|'label_name}} can be used to break an outer loop rather than the innermost loop.{{sfn|Klabnik|Nichols|2023|pp=54-56}}
Line 333 ⟶ 336:
=== Types ===
Rust is [[strongly typed]] and [[statically typed]], meaning that 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]]. [[Type inference]] is used to determine the type of variables if unspecified.{{sfn|Klabnik|Nichols|2019|pp=24}}
The type <code>()</code>, called the "unit type" in Rust, is a concrete type that has exactly one value. It occupies no memory (as it represents the absence of value). All functions that do not have an indicated return type implicitly return <code>()</code>. It is similar to {{cpp|void}} in other C-style languages, however {{cpp|void}} denotes the absence of a type and cannot have any value.
The default integer type is {{rust|i32}}, and the default [[floating point]] type is {{rust|f64}}. If the type of a [[Literal (computer programming)|literal]] number is not explicitly provided, it is either inferred from the context or the default type is used.{{sfn|Klabnik|Nichols|2019|pp=36–38}}
==== Primitive types ====
[[Integer type]]s in Rust are named based on the [[signedness]] and the number of bits the type takes. For example, {{rust|i32}} is a signed integer that takes 32 bits of storage, whereas {{
By default, integer literals are in base-10, but different [[radix|radices]] are supported with prefixes, for example, {{rust|0b11}} for [[binary number]]s, {{rust|0o567}} for [[octal]]s, and {{rust|0xDB}} for [[hexadecimal]]s. By default, integer literals default to {{rust|i32}} as its type. Suffixes such as {{rust|4u32}} can be used to explicitly set the type of a literal.{{sfn|Klabnik|Nichols|2023|pp=36-38}} Byte literals such as {{rust|b'X'}} are available to represent the [[ASCII]] value (as a {{rust|u8}}) of a specific character.{{sfn|Klabnik|Nichols|2023|p=502}}
Line 348 ⟶ 353:
<syntaxhighlight lang="rust">
let tuple: (u32,
let array: [i8; 5] = [1, 2, 3, 4, 5];
let
let value = array[2]; // 3
</syntaxhighlight>
Line 362 ⟶ 366:
<!-- todo str, and ! -->
=== Ownership and references ===
Line 379 ⟶ 384:
</syntaxhighlight>
The function {{
<syntaxhighlight lang="rust">
Line 396 ⟶ 401:
Because of these ownership rules, Rust types are known as ''[[linear types|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.<ref name="BeyondSafety">{{Cite book |last1=Balasubramanian |first1=Abhiram |last2=Baranowski |first2=Marek S. |last3=Burtsev |first3=Anton |last4=Panda |first4=Aurojit |last5=Rakamarić |first5=Zvonimir |last6=Ryzhyk |first6=Leonid |title=Proceedings of the 16th Workshop on Hot Topics in Operating Systems |chapter=System Programming in Rust |date=2017-05-07 |chapter-url=https://doi.org/10.1145/3102980.3103006 |series=HotOS '17 |___location=New York, NY, US |publisher=Association for Computing Machinery |pages=156–161 |doi=10.1145/3102980.3103006 |isbn=978-1-4503-5068-6 |s2cid=24100599 |access-date=June 1, 2022 |archive-date=June 11, 2022 |archive-url=https://web.archive.org/web/20220611034046/https://dl.acm.org/doi/10.1145/3102980.3103006 |url-status=live}}</ref>
When a value goes out of scope, it is ''dropped'' by running its [[Destructor (computer programming)|destructor]]. The destructor may be programmatically defined through implementing the {{
==== Lifetimes ====
[[Object lifetime]] refers to the period of time during which a reference is valid; that is, the time between the object creation and destruction.<ref>{{Cite web |title=Lifetimes |url=https://doc.rust-lang.org/rust-by-example/scope/lifetime.html |access-date=2024-10-29 |website=Rust by Example |archive-date=2024-11-16 |archive-url=https://web.archive.org/web/20241116192422/https://doc.rust-lang.org/rust-by-example/scope/lifetime.html |url-status=live }}</ref> These ''lifetimes'' are implicitly associated with all Rust reference types. While often inferred, they can also be indicated explicitly with named lifetime parameters (often denoted {{
Lifetimes in Rust can be thought of as [[Scope (computer science)|lexically scoped]], meaning that the duration of an object lifetime is inferred from the set of locations in the source code (i.e., function, line, and column numbers) for which a variable is valid.{{sfn|Klabnik|Nichols|2019|p=194}} For example, a reference to a local variable has a lifetime corresponding to the block it is defined in:{{sfn|Klabnik|Nichols|2019|p=194}}
Line 416 ⟶ 421:
</syntaxhighlight>
The borrow checker in the Rust compiler then enforces that references are only used in the locations of the source code where the associated lifetime is valid.{{sfn|Klabnik|Nichols|2019|pp=75,134}}<ref>{{Cite web |last=Shamrell-Harrington |first=Nell |date=2022-04-15 |title=The Rust Borrow Checker – a Deep Dive |url=https://www.infoq.com/presentations/rust-borrow-checker/ |access-date=2022-06-25 |website=InfoQ |language=en |archive-date=2022-06-25 |archive-url=https://web.archive.org/web/20220625140128/https://www.infoq.com/presentations/rust-borrow-checker/ |url-status=live }}</ref> In the example above, storing a reference to variable {{
<syntaxhighlight lang="rust">
Line 431 ⟶ 436:
</syntaxhighlight>
Since the lifetime of the referenced variable ({{
Lifetimes can be indicated using explicit ''lifetime parameters'' on function arguments. For example, the following code specifies that the reference returned by the function has the same lifetime as {{
<syntaxhighlight lang="rust">
Line 452 ⟶ 457:
==== Standard library ====
[[File:Rust standard libraries.svg|thumb|A diagram of the dependencies between the standard library modules of Rust.]]
The Rust [[standard library]] defines and implements many widely used custom data types, including core data structures such as {{
Rust uses [[Option type|<code>Option</code>]] to define optional values, which can be matched using <code>if let</code> or <code>match</code> to access the inner value:{{sfn|Klabnik|Nichols|2023|pp=108-110,113-114,116-117}}
Line 482 ⟶ 487:
=== Polymorphism ===
Rust supports [[bounded parametric polymorphism]] through [[Trait (computer programming)|traits]] and [[generic function]]s.{{sfn|Klabnik|Nichols|2023|p=378}} Common behavior between types may be declared using traits and {{rust|impl}}s:{{sfn|Klabnik|Nichols|2023|pp=192-198}}
==== Generics ====▼
<syntaxhighlight lang="rust">
trait Zero: Sized {
fn zero() -> Self;
fn is_zero(&self) -> bool
where
Self: PartialEq,
{
self == &Zero::zero()
}
}
impl Zero for u32 {
// sum is a generic function with one type parameter, T▼
fn zero() -> u32 { 0 }
}
impl Zero for f32 {
fn main() {▼
}
</syntaxhighlight>
The example above also includes a method {{rust|is_zero}} which provides a default implementation that is not required when implementing the trait.{{sfn|Klabnik|Nichols|2023|pp=192-198}}
A function can then be made generic by adding type parameters inside angle brackets ({{rust|<Num>}}), which only allow types that implement the trait:
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.{{sfn|Klabnik|Nichols|2019|pp=171–172,205}}▼
<syntaxhighlight lang="rust">
fn zero<Num: Zero>() -> Num {
Num::zero()
}
▲fn main() {
let a: u32 = zero();
let b: f32 = zero();
assert!(a.is_zero() && b.is_zero());
}
</syntaxhighlight>
In the examples above, {{rust|Num: Zero}} as well as {{rust|where Self: PartialEq}} are trait bounds that constrain the type to only allow types that implement {{rust|Zero}} or {{rust|PartialEq}}.{{sfn|Klabnik|Nichols|2023|pp=192-198}} Within a trait or impl, {{rust|Self}} refers to the type that the code is implementing.{{sfn|Klabnik|Nichols|2023|p=98}}
▲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.{{sfn|Klabnik|Nichols|2019|pp=171–172,205}}
==== Trait objects ====
However, Rust also uses a feature known as ''trait objects'' to accomplish [[dynamic dispatch]], a type of polymorphism where the implementation of a polymorphic operation is chosen at [[Runtime (program lifecycle phase)|runtime]]. This allows for behavior similar to [[duck typing]], where all data types that implement a given trait can be treated as functionally equivalent.{{sfn|Klabnik|Nichols|2023|loc=[https://doc.rust-lang.org/book/ch18-02-trait-objects.html 18.2. Using Trait Objects That Allow for Values of Different Types]}} Trait objects are declared using the syntax <code>dyn Tr</code> where <code>Tr</code> is a trait. Trait objects are dynamically sized, therefore they must be put behind a pointer, such as <code>Box</code>.{{sfn|Klabnik|Nichols|2019|pp=441–442}} The following example creates a list of objects where each object can be printed out using the <code>Display</code> trait: <syntaxhighlight lang="Rust">
Line 540 ⟶ 553:
=== Memory safety ===
Rust is designed to be [[memory safe]]. It does not permit null pointers, [[dangling pointer]]s, or [[data race]]s.<ref name="cnet">{{cite web |url=http://reviews.cnet.com/8301-3514_7-57577639/samsung-joins-mozillas-quest-for-rust/ |title=Samsung joins Mozilla's quest for Rust |last=Rosenblatt |first=Seth |date=2013-04-03 |publisher=[[CNET]] |access-date=2013-04-05 |archive-date=2013-04-04 |archive-url=https://web.archive.org/web/20130404142333/http://reviews.cnet.com/8301-3514_7-57577639/samsung-joins-mozillas-quest-for-rust/ |url-status=live}}</ref><ref name="lwn">{{cite web |last=Brown |first=Neil |date=2013-04-17 |title=A taste of Rust |url=https://lwn.net/Articles/547145/ |url-status=live |archive-url=https://web.archive.org/web/20130426010754/http://lwn.net/Articles/547145/ |archive-date=2013-04-26 |access-date=2013-04-25 |website=[[LWN.net]]}}</ref><ref name="The Rustonomicon">{{Cite web|url=https://doc.rust-lang.org/nomicon/races.html|title=Races|website=The Rustonomicon|access-date=2017-07-03|archive-date=2017-07-10|archive-url=https://web.archive.org/web/20170710194643/https://doc.rust-lang.org/nomicon/races.html|url-status=live}}</ref><ref name="Sensors">{{cite journal |last1=Vandervelden |first1=Thibaut |last2=De Smet |first2=Ruben |last3=Deac |first3=Diana |last4=Steenhaut |first4=Kris |last5=Braeken |first5=An |title=Overview of Embedded Rust Operating Systems and Frameworks |journal= Sensors|doi=10.3390/s24175818 |date=7 September 2024 |volume=24 |issue=17 |page=5818 |doi-access=free |pmid=39275729 |pmc=11398098 |bibcode=2024Senso..24.5818V }}</ref> Data values can be initialized only through a fixed set of forms, all of which require their inputs to be already initialized.<ref name="lang-faq">{{cite web |title=The Rust Language FAQ |publisher=The Rust Programming Language |url=http://static.rust-lang.org/doc/master/complement-lang-faq.html |url-status=dead |archive-url=https://web.archive.org/web/20150420104147/http://static.rust-lang.org/doc/master/complement-lang-faq.html |archive-date=2015-04-20 |year=2015 |access-date=2017-04-24}}</ref>
Unsafe code can subvert some of these restrictions, using the <code>unsafe</code> keyword.{{sfn|Klabnik|Nichols|2019|pp=418–427}} Unsafe code may also be used for low-level functionality, such as [[Volatile (computer programming)|volatile memory access]], architecture-specific intrinsics, [[type punning]], and inline assembly.{{sfn|McNamara|2021|p=139, 376–379, 395}}▼
=== Memory management ===
Line 547 ⟶ 558:
The built-in reference types using the <code>&</code> 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]].{{sfn|Klabnik|Nichols|2019|pp=70–75}} Rust's type system separates shared, [[Immutable object|immutable]] references of the form <code>&T</code> from unique, mutable references of the form <code>&mut T</code>. A mutable reference can be coerced to an immutable reference, but not vice versa.{{sfn|Klabnik|Nichols|2019|p=323}}
▲
Unsafe code is sometimes needed to implement complex data structures.<ref name="UnsafeRustUse">{{Cite journal |last1=Astrauskas |first1=Vytautas |last2=Matheja |first2=Christoph |last3=Poli |first3=Federico |last4=Müller |first4=Peter |last5=Summers |first5=Alexander J. |date=2020-11-13 |title=How do programmers use unsafe rust? |url=https://dl.acm.org/doi/10.1145/3428204 |journal=Proceedings of the ACM on Programming Languages |language=en |volume=4 |issue=OOPSLA |pages=1–27 |doi=10.1145/3428204 |issn=2475-1421|hdl=20.500.11850/465785 |hdl-access=free}}</ref> A frequently cited example is that it is difficult or impossible to implement [[doubly linked list]]s in safe Rust.<ref>{{Cite journal |last=Lattuada |first=Andrea |last2=Hance |first2=Travis |last3=Cho |first3=Chanhee |last4=Brun |first4=Matthias |last5=Subasinghe |first5=Isitha |last6=Zhou |first6=Yi |last7=Howell |first7=Jon |last8=Parno |first8=Bryan |last9=Hawblitzel |first9=Chris |date=2023-04-06 |title=Verus: Verifying Rust Programs using Linear Ghost Types |url=https://dl.acm.org/doi/10.1145/3586037 |journal=Software Artifact (virtual machine, pre-built distributions) for "Verus: Verifying Rust Programs using Linear Ghost Types" |volume=7 |issue=OOPSLA1 |pages=85:286–85:315 |doi=10.1145/3586037|hdl=20.500.11850/610518 |hdl-access=free }}</ref><ref>{{Cite journal |last=Milano |first=Mae |last2=Turcotti |first2=Julia |last3=Myers |first3=Andrew C. |date=2022-06-09 |title=A flexible type system for fearless concurrency |url=https://dl.acm.org/doi/10.1145/3519939.3523443 |journal=Proceedings of the 43rd ACM SIGPLAN International Conference on Programming Language Design and Implementation |series=PLDI 2022 |___location=New York, NY, USA |publisher=Association for Computing Machinery |pages=458–473 |doi=10.1145/3519939.3523443 |isbn=978-1-4503-9265-5|doi-access=free }}</ref><ref>{{Cite web |title=Introduction - Learning Rust With Entirely Too Many Linked Lists |url=https://rust-unofficial.github.io/too-many-lists/ |access-date=2025-08-06 |website=rust-unofficial.github.io}}</ref><ref>{{Cite journal |last=Noble |first=James |last2=Mackay |first2=Julian |last3=Wrigstad |first3=Tobias |date=2023-10-16 |title=Rusty Links in Local Chains✱ |url=https://doi.org/10.1145/3611096.3611097 |journal=Proceedings of the 24th ACM International Workshop on Formal Techniques for Java-like Programs |series=FTfJP '22 |___location=New York, NY, USA |publisher=Association for Computing Machinery |pages=1–3 |doi=10.1145/3611096.3611097 |isbn=979-8-4007-0784-1|url-access=subscription }}</ref>
Programmers using unsafe Rust are considered responsible for upholding Rust's memory and type safety requirements, for example, that no two mutable references exist pointing to the same ___location.<ref name=IsRustSafely>{{Cite journal |last=Evans |first=Ana Nora |last2=Campbell |first2=Bradford |last3=Soffa |first3=Mary Lou |date=2020-10-01 |title=Is rust used safely by software developers? |url=https://doi.org/10.1145/3377811.3380413 |journal=Proceedings of the ACM/IEEE 42nd International Conference on Software Engineering |series=ICSE '20 |___location=New York, NY, USA |publisher=Association for Computing Machinery |pages=246–257 |doi=10.1145/3377811.3380413 |isbn=978-1-4503-7121-6|arxiv=2007.00752 }}</ref> If programmers write code which violates these requirements, this results in [[undefined behavior]].<ref name=IsRustSafely/> The Rust documentation includes a list of behavior considered undefined, including accessing dangling or misaligned pointers, or breaking the aliasing rules for references.<ref>{{Cite web |title=Behavior considered undefined - The Rust Reference |url=https://doc.rust-lang.org/reference/behavior-considered-undefined.html |access-date=2025-08-06 |website=doc.rust-lang.org}}</ref>
<!--
Line 586 ⟶ 605:
<syntaxhighlight lang="rust">
#[
pub extern "C" fn exported_from_rust(x: i32) -> i32 { x + 1 }
unsafe extern "C" {
Line 593 ⟶ 612:
</syntaxhighlight>
The {{rust|#[repr(C)]}} attribute enables deterministic memory layouts for {{rust|struct}}s and {{rust|enum}}s for use across FFI boundaries.{{sfn|Gjengset|2021|pp=193-209}} External libraries such as {{
== Ecosystem ==
Line 623 ⟶ 642:
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.<ref name="Rust Book G">{{harvnb|Klabnik|Nichols|2019|loc=Appendix G – How Rust is Made and "Nightly Rust"}}</ref>
Every two or three years, a new "edition" is produced. Editions are released to allow making limited [[breaking changes]], such as promoting {{
=== IDE support ===
''rust-analyzer'' is a
== Performance ==
Since it performs no garbage collection, Rust is often faster than other memory-safe languages.<ref>{{Cite web |last1=Anderson |first1=Tim |date=2021-11-30 |title=Can Rust save the planet? Why, and why not |url=https://www.theregister.com/2021/11/30/aws_reinvent_rust/ |access-date=2022-07-11 |website=[[The Register]] |language=en |
Many of Rust's features are so-called ''zero-cost abstractions'', meaning they are optimized away at compile time and incur no runtime penalty.{{sfn|McNamara|2021|p=19, 27}} The ownership and borrowing system permits [[zero-copy]] implementations for some performance-sensitive tasks, such as [[parsing]].<ref>{{Cite book |last=Couprie |first=Geoffroy |title=2015 IEEE Security and Privacy Workshops |chapter=Nom, A Byte oriented, streaming, Zero copy, Parser Combinators Library in Rust |date=2015
Since Rust uses [[LLVM]], all performance improvements in LLVM apply to Rust also.<ref name="how-fast-is-rust">{{cite web |url=https://doc.rust-lang.org/1.0.0/complement-lang-faq.html#how-fast-is-rust? |title=How Fast Is Rust? |website=The Rust Programming Language FAQ |access-date=11 April 2019 |archive-date=28 October 2020 |archive-url=https://web.archive.org/web/20201028102013/https://doc.rust-lang.org/1.0.0/complement-lang-faq.html#how-fast-is-rust? |url-status=live}}</ref> Unlike C and C++, Rust allows for reordering struct and enum elements<ref>{{Cite book
▲Many of Rust's features are so-called ''zero-cost abstractions'', meaning they are optimized away at compile time and incur no runtime penalty.{{sfn|McNamara|2021|p=19, 27}} The ownership and borrowing system permits [[zero-copy]] implementations for some performance-sensitive tasks, such as [[parsing]].<ref>{{Cite book |last=Couprie |first=Geoffroy |title=2015 IEEE Security and Privacy Workshops |chapter=Nom, A Byte oriented, streaming, Zero copy, Parser Combinators Library in Rust |date=2015 |chapter-url=https://ieeexplore.ieee.org/document/7163218 |pages=142–148 |doi=10.1109/SPW.2015.31 |isbn=978-1-4799-9933-0 |s2cid=16608844 |archive-date=2022-10-09 |access-date=2022-10-09 |archive-url=https://web.archive.org/web/20221009201729/https://ieeexplore.ieee.org/document/7163218 |url-status=live}}</ref> [[Static dispatch]] is used by default to eliminate [[method call]]s, except for methods called on dynamic trait objects.{{sfn|McNamara|2021|p=20}} The compiler also uses [[inline expansion]] to eliminate [[function call]]s and statically-dispatched method invocations.<ref>{{Cite web |title=Code generation |url=https://doc.rust-lang.org/reference/attributes/codegen.html |access-date=2022-10-09 |website=The Rust Reference |archive-date=2022-10-09 |archive-url=https://web.archive.org/web/20221009202615/https://doc.rust-lang.org/reference/attributes/codegen.html |url-status=live}}</ref>
▲Since Rust uses [[LLVM]], all performance improvements in LLVM apply to Rust also.<ref name="how-fast-is-rust">{{cite web |url=https://doc.rust-lang.org/1.0.0/complement-lang-faq.html#how-fast-is-rust? |title=How Fast Is Rust? |website=The Rust Programming Language FAQ |access-date=11 April 2019 |archive-date=28 October 2020 |archive-url=https://web.archive.org/web/20201028102013/https://doc.rust-lang.org/1.0.0/complement-lang-faq.html#how-fast-is-rust? |url-status=live}}</ref> Unlike C and C++, Rust allows for reordering struct and enum elements<ref>{{Cite book |url=https://dlnext.acm.org/doi/abs/10.1145/3445814.3446724 |access-date=2022-07-12 |year=2021 |language=en |doi=10.1145/3445814.3446724 |quote=... While some compilers (e.g., Rust) support structure reordering [82], C & C++ compilers are forbidden to reorder data structures (e.g., struct or class) [74] ... |last1=Farshin |first1=Alireza |last2=Barbette |first2=Tom |last3=Roozbeh |first3=Amir |last4=Maguire Jr |first4=Gerald Q. |last5=Kostić |first5=Dejan |title=Proceedings of the 26th ACM International Conference on Architectural Support for Programming Languages and Operating Systems |chapter=PacketMill: Toward per-Core 100-GBPS networking |pages=1–17 |isbn=9781450383172 |s2cid=231949599 |archive-date=2022-07-12 |archive-url=https://web.archive.org/web/20220712060927/https://dlnext.acm.org/doi/abs/10.1145/3445814.3446724 |url-status=live}}</ref> to reduce the sizes of structures in memory, for better memory alignment and efficiency.{{sfn|Gjengset|2021|p=22}}
== Adoption ==
Line 658 ⟶ 675:
[[Discord]], an [[instant messaging]] software company, rewrote parts of its system in Rust for increased performance in 2020. In the same year, Dropbox announced that its [[file synchronization]] had been rewritten in Rust. [[Facebook]] ([[Meta Platforms|Meta]]) used Rust to redesign its system that manages source code for internal projects.<ref name="MITTechReview" />
In the
[[DARPA]] has a project TRACTOR (Translating All C to Rust) automatically translating C to Rust using techniques such as static analysis, dynamic analysis, and large language models.<ref>{{cite web |last1=Wallach |first1=Dan |title=TRACTOR: Translating All C to Rust |url=https://www.darpa.mil/research/programs/translating-all-c-to-rust |publisher=[[DARPA]] |access-date=3 August 2025}}</ref>
== In academic research ==
Line 664 ⟶ 683:
Rust's safety and performance have been investigated in [[programming language theory]] research.<ref>{{Cite journal |last1=Jung |first1=Ralf |last2=Jourdan |first2=Jacques-Henri |last3=Krebbers |first3=Robbert |last4=Dreyer |first4=Derek |date=2017-12-27 |title=RustBelt: securing the foundations of the Rust programming language |url=https://dl.acm.org/doi/10.1145/3158154 |journal=Proceedings of the ACM on Programming Languages |language=en |volume=2 |issue=POPL |pages=1–34 |doi=10.1145/3158154 |issn=2475-1421|hdl=21.11116/0000-0003-34C6-3 |hdl-access=free }}</ref><ref name="UnsafeRustUse"/><ref>{{Cite journal |last1=Popescu |first1=Natalie |last2=Xu |first2=Ziyang |last3=Apostolakis |first3=Sotiris |last4=August |first4=David I. |last5=Levy |first5=Amit |date=2021-10-20 |title=Safer at any speed: automatic context-aware safety enhancement for Rust |journal=Proceedings of the ACM on Programming Languages |language=en |volume=5 |issue=OOPSLA |pages=1–23 |doi=10.1145/3485480 |issn=2475-1421|doi-access=free }}</ref>
Rust's applicability to writing research software has been examined in other fields. A journal article published to ''[[Proceedings of the International Astronomical Union]]'' used Rust to simulate multi-planet systems.<ref name=ResearchSoftware1>{{Cite journal |last1=Blanco-Cuaresma |first1=Sergi |last2=Bolmont |first2=Emeline |date=2017-05-30 |title=What can the programming language Rust do for astrophysics? |url=https://www.cambridge.org/core/journals/proceedings-of-the-international-astronomical-union/article/what-can-the-programming-language-rust-do-for-astrophysics/B51B6DF72B7641F2352C05A502F3D881 |journal=[[Proceedings of the International Astronomical Union]] |language=en |volume=12 |issue=S325 |pages=341–344 |doi=10.1017/S1743921316013168 |arxiv=1702.02951 |bibcode=2017IAUS..325..341B |s2cid=7857871 |issn=1743-9213 |archive-date=2022-06-25 |access-date=2022-06-25 |archive-url=https://web.archive.org/web/20220625140128/https://www.cambridge.org/core/journals/proceedings-of-the-international-astronomical-union/article/what-can-the-programming-language-rust-do-for-astrophysics/B51B6DF72B7641F2352C05A502F3D881 |url-status=live }}</ref> An article published in ''[[Nature (journal)|Nature]]'' shared stories of bioinformaticians using Rust.<ref name="Nature"/> Both articles found that Rust has advantages for its performance and safety, and cited the [[learning curve]] as being a primary drawback to its adoption.
== Community ==
[[File:Rustacean-orig-noshadow.svg|alt=A bright orange crab icon|thumb|Some Rust users refer to themselves as Rustaceans (similar to the word [[crustacean]]) and have adopted an orange crab, Ferris, as their unofficial mascot.{{sfn|Klabnik|Nichols|2019|p=4}}<ref>{{cite web |title=Getting Started |url=https://www.rust-lang.org/learn/get-started#ferris |website=The Rust Programming Language |access-date=11 October 2020 |archive-date=1 November 2020 |archive-url=https://web.archive.org/web/20201101145703/https://www.rust-lang.org/learn/get-started#ferris |url-status=live}}</ref>]]
According to the ''[[MIT Technology Review]]'', the Rust community has been seen as "unusually friendly" to newcomers and particularly attracted people from the [[queer community]], partly due to its [[code of conduct]] which outlined a set of expectations for Rust community members to follow.<ref name="MITTechReview"/> Inclusiveness of the community has been cited as an important factor for some Rust developers.<ref name="Nature"/> Demographic data on the community has been collected and published by the Rust official blog.<ref name=StateOfRustSurvey2024>{{Cite web |title=2024 State of Rust Survey Results
According to [[GitHub]]'s ''State of the Octoverse'' project, the Rust community grew by 50.5% in 2022, making it one of the fastest growing communities,<ref>{{Cite web |title=The top programming languages |url=https://octoverse.github.com/2022/top-programming-languages |access-date=2025-06-25 |website=The State of the Octoverse |language=en-gb}}</ref> though not one of the 10 largest communities as of 2024.<ref>{{Cite web |last=Staff |first=GitHub |date=2024-10-29 |title=Octoverse: AI leads Python to top language as the number of global developers surges |url=https://github.blog/news-insights/octoverse/octoverse-2024/ |access-date=2025-06-25 |website=The GitHub Blog |language=en-US}}</ref>
Line 675 ⟶ 694:
=== Rust Foundation ===
{{Infobox organization
| name
| logo
| formation
| founders
| type
| location_country
| leader_title
| leader_name
| leader_title2
| leader_name2
| website
}}
Line 707 ⟶ 726:
=== Book sources ===
{{refbegin}}
* {{Cite book |last=Gjengset |first=Jon
* {{Cite book|last1=Klabnik|first1=Steve|url=https://books.google.com/books?id=0Vv6DwAAQBAJ|title=The Rust Programming Language (Covers Rust 2018)|last2=Nichols|first2=Carol|date=2019-08-12|publisher=No Starch Press|isbn=978-1-7185-0044-0|language=en}}
* {{Cite book|last1=Blandy|first1=Jim|last2=Orendorff|first2=Jason|last3=Tindall|first3=Leonora F. S.
* {{Cite book|last1=McNamara|first1=Tim
* {{Cite book |last1=Klabnik |first1=Steve |last2=Nichols |first2=Carol
{{refend}}
Line 734 ⟶ 753:
[[Category:Rust (programming language)| ]]
[[Category:Compiled programming languages]]▼
[[Category:Concurrent programming languages]]
[[Category:Free and open source compilers]]
Line 750 ⟶ 770:
<!-- Hidden categories below -->
[[Category:Articles with example Rust code]]
▲[[Category:Compiled programming languages]]
|