Rust


This draft deletes the entire topic.

expand all collapse all

Examples

  • 55

    println! (and its sibling, print!) provides a convenient mechanism for producing and printing text that contains dynamic data, similar to the printf family of functions found in many other languages. Its first argument is a format string, which dictates how the other arguments should be printed as text. The format string may contain placeholders (enclosed in {}) to specify that a substitution should occur:

    // No substitution -- the simplest kind of format string
    println!("Hello World");
    // Output: Hello World
    
    // The first {} is substituted with a textual representation of
    // the first argument following the format string. The second {}
    // is substituted with the second argument, and so on.
    println!("{} {} {}", "Hello", true, 42);
    // Output: Hello true 42
    

    At this point, you may be asking: How did println! know to print the boolean value true as the string "true"? {} is really an instruction to the formatter that the value should be converted to text using the Display trait. This trait is implemented for most primitive Rust types (strings, numbers, booleans, etc.), and is meant for "user-facing output". Hence, the number 42 will be printed in decimal as 42, and not, say, in binary, which is how it is stored internally.

    How do we print types, then, that do not implement Display, examples being Slices ([i32]), vectors (Vec<i32>), or options (Option<&str>)? There is no clear user-facing textual representation of these (i.e. one you could trivially insert into a sentence). To facilitate the printing of such values, Rust also has the Debug trait, and the corresponding {:?} placeholder. From the documentation: "Debug should format the output in a programmer-facing, debugging context." Let's see some examples:

    println!("{:?}", vec!["a", "b", "c"]);
    // Output: ["a", "b", "c"]
    
    println!("{:?}", Some("fantastic"));
    // Output: Some("fantastic")
    
    println!("{:?}", "Hello");
    // Output: "Hello"
    // Notice the quotation marks around "Hello" that indicate
    // that a string was printed.
    

    Debug also has a built-in pretty-print mechanism, which you can enable by using the # modifier after the colon:

    println!("{:#?}", vec![Some("Hello"), None, Some("World")]);
    // Output: [
    //    Some(
    //        "Hello"
    //    ),
    //    None,
    //    Some(
    //        "World"
    //    )
    // ]
    

    The format strings allow you to express fairly complex substitutions:

    // You can specify the position of arguments using numerical indexes.
    println!("{1} {0}", "World", "Hello");
    // Output: Hello World
    
    // You can use named arguments with format
    println!("{greeting} {who}!", greeting="Hello", who="World");
    // Output: Hello World
    
    // You can mix Debug and Display prints:
    println!("{greeting} {1:?}, {0}", "and welcome", Some(42), greeting="Hello");
    // Output: Hello Some(42), and welcome
    

    println! and friends will also warn you if you are trying to do something that won't work, rather than crashing at runtime:

    // This does not compile, since we don't use the second argument.
    println!("{}", "Hello World", "ignored");
    
    // This does not compile, since we don't give the second argument.
    println!("{} {}", "Hello");
    
    // This does not compile, since Option type does not implement Display
    println!("{}", Some(42));
    

    At their core, the Rust printing macros are simply wrappers around the format! macro, which allows constructing a string by stitching together textual representations of different data values. Thus, for all the examples above, you can substitute println! for format! to store the formatted string instead of printing it:

    let x: String = format!("{} {}", "Hello", 42);
    assert_eq!(x, "Hello 42");
    
  • 24
    // use Write trait that contains write() function
    use std::io::Write;
    
    fn main() {
        std::io::stdout().write(b"Hello, world!\n").unwrap();
    }
    
    • The std::io::Write trait is designed for objects which accept byte streams. In this case, a handle to standard output is acquired with std::io::stdout().

    • Write::write() accepts a byte slice (&[u8]), which is created with a byte-string literal (b"<string>"). Write::write() returns a Result<usize, IoError>, which contains either the number of bytes written (on success) or an error value (on failure).

    • The call to Result::unwrap() indicates that the call is expected to succeed (Result<usize, IoError> -> usize), and the value is discarded.

  • 21

    To write the traditional Hello World program in Rust, create a text file called hello.rs containing the following source code:

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

    This defines a new function called main, which takes no parameters and returns no data. This is where your program starts execution when run. This function invokes println! with a string, which displays the message on the console, followed by a newline.

    To generate a binary application, invoke the Rust compiler by passing it the name of the source file:

    $ rustc hello.rs
    

    The resulting executable will have the same name as the main source module, so to run the program on a Linux or MacOS system, run:

    $ ./hello
    Hello World!
    

    On a Windows system, run:

    C:\Rust> hello.exe
    Hello World!
    
Please consider making a request to improve this example.

Remarks

Rust is a systems programming language designed for safety, speed, and concurrency. Rust has numerous compile-time features and safety checks to avoid data races and common bugs, all with minimal or no overhead.

Versions

Stable

A new stable version will be released every 6 weeks, as described in RFC 507.

VersionRelease Date
1.0.02015-05-15
1.1.02015-06-25
1.2.02015-08-07
1.3.02015-09-17
1.4.02015-10-29
1.5.02015-12-10
1.6.02016-01-21
1.7.02016-03-03
1.8.02016-04-14
1.9.02016-05-26
1.10.02016-07-07
1.11.02016-08-18
1.12.02016-09-30
1.12.12016-10-20
1.13.02016-11-10

Beta

Beta compilers are one version ahead of the latest stable version. It is generally used for testing to ensure that no crates will be broken in the next stable release.

VersionBeta Release Date
1.14.02016-10-11

Nightly

Nightly compilers are typically two versions ahead of the latest stable, and can access unstable features.

VersionNightly Release Date
1.15.02016-10-11
Still have a question about Getting started with Rust? Ask Question

Topic Outline