Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Rust 1.21 Improves Language Syntax and Tooling

Rust 1.21 Improves Language Syntax and Tooling

This item in japanese

The Rust core team has just released Rust 1.21, bringing a new language feature making literals more flexible, library stabilizations, and improved support for tools.

Rust new language feature allows to promote literals to values that are stored in static memory instead of on the stack, which makes it possible to safely take a reference to them and pass it around. Thanks to this, the following code is now legal:

    let x: &'static u32 = &5;
    thread::spawn(move || {
        println!("{}", x);

In previous versions of Rust, the compiler would reject that code complaining about the lifetime of the 5 literal, referenced through x in the thread body. The problem here is that 5 would be allocated on the stack, and would thus disappear at the exit of the function. To make the literal lifetime extends through stack rewinding, Rust 1.21 compiler translates that into roughly the following code:

    static FIVE: i32 = 5;
    let x = &FIVE;

On the tooling front, the compiler is now less memory hungry thanks to running LLVM while the translation phase is still in progress. This has two benefits: effectively parallelizing the two phases and allowing the main thread to switch between either translation or running LLVM. Additionally, rustup now supports the installation of the Rust language server (RLS) running rustup component add rls-preview. According to Rust core developers, this is the first step to make Rust tools, including RLS, Clippy, and rustfmt, work just fine with the stable release of Rust and not require a nightly build.

Speaking of library stabilizations, Iterator::for_each can now replace a for loop like in the following code:

// old
for i in 0..10 {
    println!("{}", i);

// new
(0..10).for_each(|i| println!("{}", i));

This change makes it easier to chain a number of iterators together, like in the following example:

    .map(|x| x + 1)
    .filter(|x| x % 2 == 0)
    .for_each(|i| println!("{}", i));

Additionally, the max and min functions are now stable on the Ord trait, which is used for types that form a total order set. The single and threaded reference counters, Rc<T> and Arc<T>, provide now a friendlier interface which includes From<&[T]> where T: Clone, From<str>, From<String>, From<Box<T>> where T: ?Sized, and From<Vec<T>>.

You can get the latest version of Rust running rustup update stable. For more details about what is new, do not miss the 1.21 release note.

Rate this Article