This draft deletes the entire topic.
Examples
-
println!
(and its sibling,print!
) provides a convenient mechanism for producing and printing text that contains dynamic data, similar to theprintf
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 valuetrue
as the string "true"?{}
is really an instruction to the formatter that the value should be converted to text using theDisplay
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 theDebug
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 substituteprintln!
forformat!
to store the formatted string instead of printing it:let x: String = format!("{} {}", "Hello", 42); assert_eq!(x, "Hello 42");
-
// 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 withstd::io::stdout()
. -
Write::write()
accepts a byte slice (&[u8]
), which is created with a byte-string literal (b"<string>"
).Write::write()
returns aResult<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.
-
-
-
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 invokesprintln!
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!
-
#![feature(start, libc, lang_items)] #![no_std] #![no_main] // The libc crate allows importing functions from C. extern crate libc; // A list of C functions that are being imported extern { pub fn printf(format: *const u8, ...) -> i32; } #[no_mangle] // The main function, with it's input arguments ignored, and an exit status is returned pub extern fn main(_nargs: i32, _args: *const *const u8) -> i32 { // Print "Hello, World" to stdout using printf unsafe { printf(b"Hello, World!\n" as *const u8); } // Exit with a return status of 0. 0 } #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "panic_fmt"] extern fn panic_fmt() -> ! { panic!() }
Versions
Stable
A new stable version will be released every 6 weeks, as described in RFC 507.
Version | Release Date |
---|---|
1.0.0 | 2015-05-15 |
1.1.0 | 2015-06-25 |
1.2.0 | 2015-08-07 |
1.3.0 | 2015-09-17 |
1.4.0 | 2015-10-29 |
1.5.0 | 2015-12-10 |
1.6.0 | 2016-01-21 |
1.7.0 | 2016-03-03 |
1.8.0 | 2016-04-14 |
1.9.0 | 2016-05-26 |
1.10.0 | 2016-07-07 |
1.11.0 | 2016-08-18 |
1.12.0 | 2016-09-30 |
1.12.1 | 2016-10-20 |
1.13.0 | 2016-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.
Version | Beta Release Date |
---|---|
1.14.0 | 2016-10-11 |
Nightly
Nightly compilers are typically two versions ahead of the latest stable, and can access unstable features.
Version | Nightly Release Date |
---|---|
1.15.0 | 2016-10-11 |
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft