Rust (programming language)
Paradigm | Multi-paradigm: compiled, concurrent, functional, imperative, structured, generic |
---|---|
Designed by | Originally Graydon Hoare, then Rust Project Developers |
Developer | Rust Project Developers |
First appeared | 2010 |
Stable release |
1.13[1]
/ November 10, 2016 |
Typing discipline | static, strong, inferred, nominal, linear |
Implementation language | Rust |
OS | Linux, OS X, Windows, FreeBSD, Android, iOS (partial)[2] |
License | Apache License 2.0 or MIT License[3] |
Filename extensions | .rs, .rlib |
Website |
www |
Influenced by | |
Alef,[4] C#,[4] C++,[4] Cyclone,[4][5] Erlang,[4] Haskell,[4] Hermes,[4] Limbo,[4] Newsqueak,[4] NIL,[4] OCaml,[4] Ruby,[4] Scheme,[4] Standard ML,[4] Swift[4][6] | |
Influenced | |
C# 7,[7] Crystal, Elm,[8] Idris,[9] Swift[10] |
Rust is a general-purpose, multi-paradigm, compiled programming language sponsored by Mozilla Research.[11] It is designed to be a "safe, concurrent, practical language",[12] supporting functional and imperative-procedural paradigms.
The language grew out of a personal project by Mozilla employee Graydon Hoare. Mozilla began sponsoring the project in 2009[12] and announced it in 2010.[13] The same year, work shifted from the initial compiler (written in OCaml) to the self-hosting compiler written in Rust.[14] Known as rustc, it successfully compiled itself in 2011.[15] rustc uses LLVM as its back end.
The first numbered pre-alpha release of the Rust compiler occurred in January 2012.[16] Rust 1.0, the first stable release, was released on May 15, 2015.[17]
Although its development is sponsored by Mozilla, it is an open community project. The design of the language has been refined through the experiences of writing the Servo[18] web browser layout engine and the Rust compiler. A large portion of current commits are from community members.[19]
Rust won the first place for Most Loved Programming Language of 2016 in the Stack Overflow Developer Survey.[20] The language is believed to take its name from the rust family of fungi.[21]
Design
The goal of Rust is to be a language suited to creating highly concurrent and highly safe systems,[22] and programming in the large. This has led to a feature set with an emphasis on safety, control of memory layout, and concurrency. Performance of idiomatic Rust is comparable to the performance of idiomatic C++.[23][24]
The syntax of Rust is similar to C and C++, with blocks of code delimited by curly brackets, and control flow keywords such as if
, else
, while
, and for
. Not all C or C++ keywords are present, however, while some Rust keywords (such as match
for multi-directional branching, similar to switch
in other languages) will be less familiar to programmers coming from these languages. Despite the syntactic resemblance, Rust is semantically very different from C and C++.
The system is designed to be memory safe, and it does not permit null pointers or dangling pointers.[25][26] Data values can only be initialized through a fixed set of forms, all of which require their inputs to be already initialized.[27]
The type system supports a mechanism similar to type classes, called 'traits', inspired directly by the Haskell language. This is a facility for ad-hoc polymorphism, achieved by adding constraints to type variable declarations. Other features from Haskell, such as higher-kinded polymorphism, are not yet supported.
Rust does not use an automated garbage collection system like those used by Go, Java or .NET Framework, but instead Resource Acquisition Is Initialization (RAII), as in C++.
Rust features type inference, for variables declared with the let
keyword. 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 fails to assign a value to the variable.[28] Functions can be given generic parameters but they must be explicitly bounded by traits. There is no way to leave off type signatures while still making use of methods and operators on the parameters.
The object 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 impl
keyword. Inheritance and polymorphism are provided by traits; 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, to prevent the diamond problem of multiple inheritance, as in C++.
History
In addition to conventional static typing, before version 0.4, Rust also supported typestates. The typestate system modeled assertions before and after program statements, through use of a special check
statement. Discrepancies could be discovered at compile time, rather than when a program was running, as might be the case with assertions in C or C++ code. The typestate concept was not unique to Rust, as it was first introduced in the language NIL.[29] Typestates were removed because in practice they found little use, though the same functionality can still be achieved with branding patterns.[30]
The style of the object system changed considerably within versions 0.2, 0.3 and 0.4 of Rust. Version 0.2 introduced classes for the first time, with version 0.3 adding a number of features including destructors and polymorphism through the use of interfaces. In Rust 0.4, traits were added as a means to provide inheritance; interfaces were unified with traits and removed as a separate feature. Classes were also removed, replaced by a combination of implementations and structured types.
Starting in Rust 0.9 and ending in Rust 0.11, Rust had two built-in pointer types, ~
and @
, simplifying the core memory model. It reimplemented those pointer types in the standard library as Box
and (the now removed) Gc
.
In January 2014, the editor-in-chief of Dr Dobb's, Andrew Binstock, commented on Rust's chances to become a competitor to C++, as well as to the other upcoming languages D, Go and Nim (then Nimrod): according to Binstock, while Rust was "widely viewed as a remarkably elegant language", adoption of it stayed behind because the language kept changing between versions.[31] The first "stable" version of the Rust, version 1.0.0, was released in May 2015.[32]
Rust was the third most loved programming language in the 2015 Stack Overflow annual survey,[33] and jumped to the first place in 2016 Stack Overflow annual survey.[34]
Projects using Rust
- Firefox[35]
- Magic Pocket – Dropbox's file system that powers their Diskotech petabyte storage machines.[36]
- Servo – Mozilla's new parallel web browser engine[37] developed in collaboration with Samsung.[38]
- Cargo - Rust's build system
- OpenDNS – Uses Rust in two of its components.[39][40][41]
- Redox OS – a microkernel operating system being developed in Rust.[42]
- Quantum – a web engine with many components developed in Rust by Mozilla.[43]
Examples
Hello world
This program prints the string "Hello, world!" to standard output and exits.
fn main() {
println!("Hello, world!");
}
Factorial
This is a factorial function, implemented recursively. The branches in this function exhibit Rust's optional implicit return values, which can be utilized where a more "functional" style is preferred. Unlike C++ and related languages, Rust's if
construct is an expression rather than a statement, and thus has a return value of its own.
fn factorial_recursive(n: u32) -> u32 {
if n <= 1 {
1
} else {
n * factorial_recursive(n - 1)
}
}
And here's an iterative implementation:
fn factorial_iterative(n: u32) -> u32 {
// Variables are declared with `let`.
// The `mut` keyword allows these variables to be mutated.
let mut result = 1;
for i in 2..n+1 { // The lower bound is inclusive, the upper bound exclusive.
result *= i;
}
return result; // An explicit return, in contrast to the prior function.
}
This implementation uses an iterator instead.
fn factorial_iterator(n: u32) -> u32 {
// |accum, x| defines an anonymous function.
// Optimizations like inline expansion reduce the range and fold
// to have performance similar to factorial_iterative.
(1..n + 1).fold(1, |accum, x| accum * x)
}
Concurrency
A demonstration of Rust's concurrency capabilities:
use std::thread;
// This function creates ten threads that all execute concurrently.
// To verify this, run the program several times and observe the irregular
// order in which each thread's output is printed.
fn main() {
// This string is immutable, so it can safely be accessed from multiple threads.
let greeting = "Hello";
let mut threads = Vec::new();
// `for` loops work with any type that implements the `Iterator` trait.
for num in 0..10 {
threads.push(thread::spawn(move || {
// `println!` is a macro that statically typechecks a format string.
// Macros are structural (as in Scheme) rather than textual (as in C).
println!("{} from thread number {}", greeting, num);
}));
}
// Join each thread so that they all finish before program exit.
for thread in threads {
thread.join().unwrap();
}
}
Miscellaneous
A demonstration of Rust's built-in unique smart pointers, along with tagged unions and methods.
use IntList::{Node, Empty};
// This program defines a recursive data structure and implements methods upon it.
// Recursive data structures require a layer of indirection, which is provided here
// by a unique pointer, constructed via the `Box::new` constructor. These are
// analogous to the C++ library type `std::unique_ptr`, though with more static
// safety guarantees.
fn main() {
let list = IntList::new().prepend(3).prepend(2).prepend(1);
println!("Sum of all values in the list: {}.", list.sum());
println!("Sum of all doubled values in the list: {}.", list.multiply_by(2).sum());
}
// `enum` defines a tagged union that may be one of several different kinds of values at runtime.
// The type here will either contain no value, or a value and a pointer to another `IntList`.
enum IntList {
Node(i32, Box<IntList>),
Empty
}
// An `impl` block allows methods to be defined on a type.
impl IntList {
fn new() -> Box<IntList> {
Box::new(Empty)
}
fn prepend(self, value: i32) -> Box<IntList> {
Box::new(Node(value, Box::new(self)))
}
fn sum(&self) -> i32 {
// `match` expressions are the typical way of employing pattern-matching,
// and are somewhat analogous to the `switch` statement from C and C++.
match *self {
Node(value, ref next) => value + next.sum(),
Empty => 0
}
}
fn multiply_by(&self, n: i32) -> Box<IntList> {
match *self {
Node(value, ref next) => Box::new(Node(value * n, next.multiply_by(n))),
Empty => Box::new(Empty)
}
}
}
See also
References
- ↑ "Announcing Rust 1.13". blog.rust-lang.org. 10 November 2016. Retrieved 10 November 2016.
- ↑ "Doc building for ios". GitHub. Retrieved 4 January 2015.
- ↑ "Copyright". Rust compiler source repository. Retrieved 2015-11-09.
- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 "The Rust Reference: Appendix: Influences". Retrieved March 25, 2015.
Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed): SML, OCaml [...] C++ [...] ML Kit, Cyclone [...] Haskell [...] Newsqueak, Alef, Limbo [...] Erlang [...] Swift [...] Scheme [...] C# [...] Ruby [...] NIL, Hermes
- ↑ "Note Research: Type System". 2015-02-01. Retrieved 2015-03-25.
Papers that have had more or less influence on Rust, or which one might want to consult for inspiration or to understand Rust's background. [...] Region based memory management in Cyclone [...] Safe memory management in Cyclone
- ↑ "RFC for `if let` expression". Retrieved December 4, 2014.
The `if let` construct is based on the precedent set by Swift, which introduced its own `if let` statement.
- ↑ "Discussion - Patterns and Records". 2015-03-25. Retrieved 2015-03-25.
Sources of Inspiration: [...] Rust
- ↑ "Command Optimizations?". 2014-06-26. Retrieved 2014-12-10.
I just added the outline of a Result library that lets you use richer error messages. It's like Either except the names are more helpful. The names are inspired by Rust's Result library.
- ↑ "Uniqueness Types". 2014-08-22. Archived from the original on December 25, 2014. Retrieved 2014-10-27.
They are inspired by linear types, Uniqueness Types in the Clean programming language, and ownership types and borrowed pointers in the Rust programming language.
- ↑ Lattner, Chris (2014-06-03). "Chris Lattner's Homepage". Chris Lattner. Retrieved 2014-06-03.
The Swift language is the product of tireless effort from a team of language experts, documentation gurus, compiler optimization ninjas, and an incredibly important internal dogfooding group who provided feedback to help refine and battle-test ideas. Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
- ↑ Noel (2010-07-08). "The Rust Language". Lambda the Ultimate. Retrieved 2010-10-30.
- 1 2 "FAQ - The Rust Project". Rust-lang.org. Retrieved 2 March 2016.
- ↑ "Future Tense". 2011-04-29. Retrieved 2012-02-06.
At Mozilla Summit 2010, we launched Rust, a new programming language motivated by safety and concurrency for parallel hardware, the “manycore” future which is upon us.
- ↑ Hoare, Graydon (2010-10-02). "Rust Progress". Archived from the original on 2014-08-15. Retrieved 2010-10-30.
- ↑ Hoare, Graydon (2011-04-20). "[rust-dev] stage1/rustc builds". Retrieved 2011-04-20.
After that last change fixing the logging scope context bug, looks like stage1/rustc builds. Just shy of midnight :)
- ↑ catamorphism (2012-01-20). "Mozilla and the Rust community release Rust 0.1 (a strongly-typed systems programming language with a focus on memory safety and concurrency)". Retrieved 2012-02-06.
- ↑ "Announcing Rust 1.0 - The Rust Programming Language Blog". blog.rust-lang.org. The Rust Core Team. Retrieved 21 January 2016.
- ↑ Peter Bright (2013-04-03). "Samsung teams up with Mozilla to build browser engine for multicore machines". Arstechnica.com. Retrieved 2013-04-04.
- ↑ "Contributors to rust-lang/rust · GitHub". Github.com. Retrieved 2016-11-03.
- ↑
- ↑ "Internet archaeology: the definitive, end-all source for why Rust is named "Rust" : rust". Reddit.com. 2014-06-07. Retrieved 2016-11-03.
- ↑ Avram, Abel (2012-08-03). "Interview on Rust, a Systems Programming Language Developed by Mozilla". InfoQ. Retrieved 2013-08-17.
GH: A lot of obvious good ideas, known and loved in other languages, haven't made it into widely used systems languages... There were a lot of good competitors in the late 1970s and early 1980s in that space, and I wanted to revive some of their ideas and give them another go, on the theory that circumstances have changed: the internet is highly concurrent and highly security-conscious, so the design-tradeoffs that always favor C and C++ (for example) have been shifting.
- ↑ Walton, Patrick (2010-12-05). "C++ Design Goals in the Context of Rust". Retrieved 2011-01-21.
... It’s impossible to be “as fast as C” in all cases while remaining safe... C++ allows all sorts of low-level tricks, mostly involving circumventing the type system, that offer practically unlimited avenues for optimization. In practice, though, C++ programmers restrict themselves to a few tools for the vast majority of the code they write, including stack-allocated variables owned by one function and passed by alias, uniquely owned objects (often used with
auto_ptr
or the C++0xunique_ptr
), and reference counting viashared_ptr
or COM. One of the goals of Rust’s type system is to support these patterns exactly as C++ does, but to enforce their safe usage. In this way, the goal is to be competitive with the vast majority of idiomatic C++ in performance, while remaining memory-safe... - ↑ "How Fast Is Rust?". The Rust Programming Language FAQ. Retrieved 3 August 2016.
- ↑ Rosenblatt, Seth (2013-04-03). "Samsung joins Mozilla's quest for Rust". Retrieved 2013-04-05.
[Brendan Eich] noted that every year browsers fall victim to hacking in the annual Pwn2Own contest at the CanSecWest conference. "There's no free memory reads" in Rust, he said, but there are in C++. Those problems "lead to a lot of browser vulnerabilities" and would be solved by Rust, which is a self-compiling language.
- ↑ Brown, Neil (2013-04-17). "A taste of Rust". Retrieved 2013-04-25.
... Other more complex data structures could clearly be implemented to allow greater levels of sharing, while making sure the interface is composed only of owned and managed references, and thus is safe from unplanned concurrent access and from dangling pointer errors.
- ↑ "Doc language FAQ". Github.com. 2010-09-14. Retrieved 2012-01-11.
- ↑ Walton, Patrick (2010-10-01). "Rust Features I: Type Inference". Retrieved 2011-01-21.
- ↑ Strom, Robert E.; Yemini, Shaula (1986). "Typestate: A Programming Language Concept for Enhancing Software Reliability" (PDF). IEEE Transactions on Software Engineering. ISSN 0098-5589. Retrieved 2010-11-14.
- ↑ Walton, Patrick (2012-12-26). "Typestate Is Dead, Long Live Typestate!". Pcwalton.github.com. Retrieved 2016-11-03.
- ↑ Binstock, Andrew. "The Rise And Fall of Languages in 2013". Dr Dobb's.
- ↑ The Rust Core Team (May 15, 2015). "Announcing Rust 1.0". Retrieved 2015-12-11.
- ↑ "Stack Overflow Developer Survey 2015". Stackoverflow.com. Retrieved 2016-11-03.
- ↑ "Stack Overflow Developer Survey 2016". Stackoverflow.com. Retrieved 2016-12-02.
- ↑ Herman, Dave (2016-07-12). "Shipping Rust in Firefox ★ Mozilla Hacks – the Web developer blog". Hacks.mozilla.org. Retrieved 2016-11-03.
- ↑ "The Epic Story of Dropbox's Exodus From the Amazon Cloud Empire". Wired.com. 2016-03-14. Retrieved 2016-11-03.
- ↑ Serdar Yegulalp (3 April 2015). "Mozilla's Rust-based Servo browser engine inches forward". InfoWorld. Retrieved 2016-03-15.
- ↑ Frederic Lardinois (3 April 2015). "Mozilla And Samsung Team Up To Develop Servo, Mozilla's Next-Gen Browser Engine For Multicore Processors". TechCrunch.
- ↑ Balbaert, Ivo. Rust Essentials. Packt Publishing. p. 6. ISBN 1785285769. Retrieved 21 March 2016.
- ↑ Frank, Denis. "Using HyperLogLog to Detect Malware Faster Than Ever". OpenDNS Security Labs. Retrieved 19 March 2016.
- ↑ Denis, Frank. "ZeroMQ: Helping us Block Malicious Domains in Real Time". OpenDNS Security Labs. Retrieved 19 March 2016.
- ↑ Yegulalp, Serdar. "Rust's Redox OS could show Linux a few new tricks". infoworld. Retrieved 21 March 2016.
- ↑ Bryant, David. "A Quantum Leap for the Web". Medium. Retrieved 27 October 2016.
External links
- Official website
- The Rust-dev Archives – electronic mailing list
- rust on GitHub – primary source code repository and bug tracker
- rust-rosetta on GitHub – implementations of common algorithms and solutions
- Rust by Example – web book
- Rust SubReddit – active dev community language development and support