Rust (programming language): Difference between revisions

Content deleted Content added
 
(12 intermediate revisions by 6 users not shown)
Line 68:
}}
 
'''Rust''' is a text-based [[General-purpose programming language|general-purpose]] [[programming language]] emphasizing [[Computer performance|performance]], [[type safety]], and [[Concurrency (computer science)|concurrency]]. It enforces [[memory safety]], meaning that all [[Reference (computer science)|references]] point to valid memory. It does so 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]].
 
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.
Line 137:
 
=== 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 {{rust|foo}} of type {{rust|i32}} and outputs its value.
 
<syntaxhighlight lang="rust">
Line 267:
 
<syntaxhighlight lang="rust">
(1..=100).filter(|&x: i8| -> bool { x % 3 == 0 }).sum()
</syntaxhighlight>
 
Line 333:
=== 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}}
Line 452 ⟶ 454:
 
==== 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|Vec}}, {{rust|Option}}, and {{rust|HashMap}}, as well as [[smart pointer]] types. Rust also provides a way to exclude most of the standard library using the attribute {{rust|#![no_std]}}, for applications such as embedded devices. Internally, the standard library is divided into three parts, {{rust|core}}, {{rust|alloc}}, and {{rust|std}}, where {{rust|std}} and {{rust|alloc}} are excluded by {{rust|#![no_std]}}.{{sfn|Gjengset|2021|pp=213-215}}
 
Line 528 ⟶ 530:
Generic functions use [[static dispatch]], meaning that the type of all parameters that end up being used for the function must be known at compile time. Generic functions generate separate copies of the code for each combination of generic parameters used in a process called [[monomorphization]].{{sfn|Klabnik|Nichols|2023|pp=191-192}} Because monomorphization duplicates the code for each type used, it is as performant as writing functions using concrete types,{{sfn|Klabnik|Nichols|2023|pp=191-192}} but compile time and size of the output binary could be increased.{{sfn|Gjengset|2021|p=25}}
 
howeverHowever, 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 558 ⟶ 560:
Rust's memory safety checks may be circumvented through the use of {{rust|unsafe}} blocks. This allows programmers to deference arbitrary raw pointers, call external code, or perform other low-level functionality not allowed by safe Rust.{{sfn|Klabnik|Nichols|2023|pp=420-429}} Some low-level functionality enabled in this way includes [[Volatile (computer programming)|volatile memory access]], architecture-specific intrinsics, [[type punning]], and inline assembly.{{sfn|McNamara|2021|p=139, 376–379, 395}}
 
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>
<!--