Benutzer:Thoeppner/Artikelentwurf Rust (Programmiersprache)

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
Rust
Basisdaten
Paradigmen: kompiliert, concurrent, functional, imperative, object-oriented, structured
Erscheinungsjahr: 2012
Designer: Graydon Hoare
Entwickler: Rust Project Developers
Aktuelle Version: 0.10[1]  (Vorlage:Release date and age)
Typisierung: statisch, stark, strukturell, mit Typinferenz
Beeinflusst von: Alef, C#, C++, Camlp4, Common Lisp, Cyclone, Erlang, Haskell, Hermes, Limbo, Napier, Napier88, Newsqueak, NIL, Ocaml, Racket, Ruby, Sather, Standard ML
Betriebssystem: Linux, Mac OS X, Windows, FreeBSD, Android
Lizenz: Apache Lizenz 2.0 or MIT Lizenz[2]
rust-lang.org

Rust is a general purpose, multi-paradigm, compiled programming language developed by Mozilla Research.[3] It is designed to be a "safe, concurrent, practical language",[4][5] supporting pure-functional, concurrent-actor, imperative-procedural, and object-oriented styles.

The language grew out of a personal project by lead developer Graydon Hoare, who began work on it in 2006; his employer Mozilla became involved in 2009[6] and officially unveiled it for the first time in 2010.[7] The same year, work shifted from the initial compiler (written in OCaml) to the self-hosted compiler written in Rust itself.[8] Known as rustc, it successfully compiled itself in 2011.[9] The self-hosted compiler uses LLVM as its backend.

The first numbered alpha release of the Rust compiler occurred in January 2012.[10] The current release is version 0.10, released in April 2014.[1]

Rust is developed entirely in the open and solicits feedback and contributions from the community. The design of the language has been refined through the experiences of writing the Servo[11] layout engine and the Rust compiler itself. Although its development is sponsored by Mozilla and Samsung, it is a community project. A large portion of current commits are from community members.[12]

The goal of Rust is to be a good language for the creation of large client and server programs that run over the Internet.[13] This has led to a feature set with an emphasis on safety, control of memory layout and concurrency. Performance of safe code is expected to be slower than C++ if performance is the only consideration, but to be comparable to C++ code that manually takes precautions comparable to what the Rust language mandates.[14]

The syntax of Rust is similar to C and C++, with blocks of code delimited by curly braces, and control-flow keywords such as if, else, do, while, and for. Not all C or C++ keywords are present, however, while others (such as the match keyword for multi-directional branching) 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.[15][16] Data values can only be initialized through a fixed set of forms, all of which require their inputs to be already initialized.[17] A system of pointer lifetimes and freezing allows the compiler to prevent many types of error that are possible to write in C++, even when using its smart pointers.

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 features type inference, for variables declared with the let keyword. Such variables do not require a value to be initially assigned in order to determine their type. A compile-time error results if any branch of code fails to assign a value to the variable.[18] 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.

Concurrency is supported through lightweight tasks, similar to those found in Erlang and other actor-based languages. In such systems, tasks communicate via message passing, rather than sharing data directly. For performance reasons, it is possible to send data without copying, using unique boxes. Unique boxes are guaranteed to only have one owner, and can be released by the sending task for use by the receiver.

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, in order to prevent the diamond inheritance problem of C++.

The following code examples are valid as of Rust 0.9. Syntax and semantics may change in subsequent versions.

Hello world:

fn main() {
    println!("Hello world!");
}

Two versions of the factorial function, in both recursive and iterative styles:

/* 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 recursive_factorial(n: int) -> int {
    if n <= 1 { 1 }
    else { n * recursive_factorial(n-1) }
}

fn iterative_factorial(n: int) -> int {
    // Variables (or more correctly, bindings) are declared with `let`.
    // The `mut` keyword allows these variables to be mutated.
    let mut i = 1;
    let mut result = 1;
    while i <= n {
        result *= i;
        i += 1;
    }
    return result; // An explicit return, in contrast to the prior function.
}

fn main() {
    println!("Recursive result: {:i}", recursive_factorial(10));
    println!("Iterative result: {:i}", iterative_factorial(10));
}

A simple demonstration of Rust's lightweight concurrency capabilities:

/* This function creates ten "tasks" that all execute concurrently. Run it
   several times and observe the irregular output that results as each task
   races on stdout, due to the fact that each task may yield both between
   successive calls to `println` and within the `println` function itself. */
fn main() {
    // This string is immutable, so it can safely be accessed from multiple tasks.
    let message = "This is part of a lightweight thread.";
    // `for` loops work with any type that implements the `Iterator` trait.
    for num in range(0, 10) {
        spawn(proc() {
            println(message);
            // `println!` is a macro that statically verifies a format string.
            // Macros are structural (as in Scheme) rather than textual (as in C).
            println!("Message printed by task {:i}.", num);
        });
    }
}

A demonstration of pattern matching, inspired by the ML family of languages:

fn main() {
    let argv = std::os::args();

    // The tuple returned by `match` will be destructured into two independent variables.
    let (first, last) = match argv {
        // The following pattern will match any vector that has the specified structure.
        // The first element in `argv`, the filename, is ignored with the underscore pattern.
        // The double-dot pattern will cause zero or more elements to be ignored.
        [_, first_arg, .., last_arg] => (first_arg, last_arg),

        // The underscore pattern is again used here as a default case,
        // ignoring all vectors that do not match the prior pattern.
        _ => fail!("Error: At least two arguments expected.")
    };

    println!("The first argument was {:s}, \
              and the last argument was {:s}.", first, last);
}

A demonstration of Rust's built-in unique smart pointers, along with tagged unions and methods:

/* This program defines a recursive datastructure and implements methods upon it.
   Recursive datastructures require a layer of indirection, which is provided here
   by a unique pointer, indicated by the tilde `~` operator. These are analogous to
   the C++ library type `std::unique_ptr`, though with more static safety guarantees. */
fn main() {
    let list = ~Node(1, ~Node(2, ~Node(3, ~Empty)));
    println!("Sum of all values in the list: {:i}.", 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(int, ~IntList),
    Empty
}

// An `impl` block allows methods to be defined on a type.
impl IntList {
    fn sum(~self) -> int {
        // As in C and C++, pointers are dereferenced with the asterisk `*` operator.
        match *self {
            Node(value, next) => value + next.sum(),
            Empty => 0
        }
    }

    fn multiply_by(~self, n: int) -> ~IntList {
        match *self {
            Node(value, next) => ~Node(value * n, next.multiply_by(n)),
            Empty => ~Empty
        }
    }
}

Sprachentwicklung

[Bearbeiten | Quelltext bearbeiten]

In addition to conventional static typing, prior to 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 once 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 NIL programming language.[19] Typestates were removed because in practice they found little use, though the same functionality can still be achieved with branding patterns.[20]

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.

Release History
Version Date
0.10 2014-04-03
0.9 2014-01-09
0.8 2013-09-26
0.7 2013-07-03
0.6 2013-04-02
0.5 2012-12-20
0.4 2012-10-12
0.3 2012-07-12
0.2 2012-03-28
0.1 2012-01-20

The releases of the rust compiler are available at https://github.com/mozilla/rust/releases.

Einzelnachweise

[Bearbeiten | Quelltext bearbeiten]
  1. a b Rust Release Notes
  2. COPYRIGHT. Rust compiler source repository, abgerufen am 17. Dezember 2012.
  3. The Rust Language. Lambda the Ultimate, 8. Juli 2010, abgerufen am 30. Oktober 2010.
  4. The Rust Programming Language. Abgerufen am 21. Oktober 2012.
  5. Doc language FAQ. Abgerufen am 21. Oktober 2012.
  6. Project FAQ. 14. September 2010, abgerufen am 11. Januar 2012.
  7. Future Tense. 29. April 2011, abgerufen am 6. Februar 2012: „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.“
  8. Graydon Hoare: Rust Progress. 2. Oktober 2010, abgerufen am 30. Oktober 2010.
  9. Graydon Hoare: [rust-dev] stage1/rustc builds. 20. April 2011, abgerufen am 20. April 2011: „After that last change fixing the logging scope context bug, looks like stage1/rustc builds. Just shy of midnight :)“
  10. catamorphism: Mozilla and the Rust community release Rust 0.1 (a strongly-typed systems programming language with a focus on memory safety and concurrency). 20. Januar 2012, abgerufen am 6. Februar 2012.
  11. Peter Bright: Samsung teams up with Mozilla to build browser engine for multicore machines. 3. April 2013, abgerufen am 4. April 2013.
  12. Rust Contributors.
  13. Abel Avram: Interview on Rust, a Systems Programming Language Developed by Mozilla. InfoQ, 3. August 2012, abgerufen am 17. August 2013: „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 70s and early 80s 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.“
  14. Patrick Walton: C++ Design Goals in the Context of Rust. 5. Dezember 2010, abgerufen am 21. Januar 2011: „… 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++0x unique_ptr), and reference counting via shared_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…“
  15. Seth Rosenblatt: Samsung joins Mozilla's quest for Rust. 3. April 2013, abgerufen am 5. April 2013: „[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.“
  16. Neil Brown: A taste of Rust. 17. April 2013, abgerufen am 25. April 2013: „… 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.“
  17. Doc language FAQ. 14. September 2010, abgerufen am 11. Januar 2012.
  18. Patrick Walton: Rust Features I: Type Inference. 1. Oktober 2010, abgerufen am 21. Januar 2011.
  19. Robert E. Strom, Shaula Yemini: Typestate: A Programming Language Concept for Enhancing Software Reliability. IEEE Transactions on Software Engineering, 1986, ISSN 0098-5589 (cmu.edu [PDF; abgerufen am 14. November 2010]).
  20. Typestate Is Dead, Long Live Typestate! 26. Dezember 2012, abgerufen am 28. Dezember 2012.

{Mozilla Projekte}