Skip to Content
Programming Rust
book

Programming Rust

by Jim Blandy, Jason Orendorff
December 2017
Intermediate to advanced content levelIntermediate to advanced
619 pages
15h 11m
English
O'Reilly Media, Inc.
Content preview from Programming Rust

Chapter 6. Expressions

LISP programmers know the value of everything, but the cost of nothing.

Alan Perlis, epigram #55

In this chapter, we’ll cover the expressions of Rust, the building blocks that make up the body of Rust functions. A few concepts, such as closures and iterators, are deep enough that we will dedicate a whole chapter to them later on. For now, we aim to cover as much syntax as possible in a few pages.

An Expression Language

Rust visually resembles the C family of languages, but this is a bit of a ruse. In C, there is a sharp distinction between expressions, bits of code that look something like this:

5 * (fahr-32) / 9

and statements, which look more like this:

for (; begin != end; ++begin) {
    if (*begin == target)
        break;
}

Expressions have values. Statements don’t.

Rust is what is called an expression language. This means it follows an older tradition, dating back to Lisp, where expressions do all the work.

In C, if and switch are statements. They don’t produce a value, and they can’t be used in the middle of an expression. In Rust, if and match can produce values. We already saw a match expression that produces a numeric value in Chapter 2:

pixels[r * bounds.0 + c] =
    match escapes(Complex { re: point.0, im: point.1 }, 255) {
        None => 0,
        Some(count) => 255 - count as u8
    };

An if expression can be used to initialize a variable:

let status =
    if cpu.temperature <= MAX_TEMP {
        HttpStatus::Ok
    } else {
        HttpStatus::ServerError  // server melted
    };

A match ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Rust Programming Language

The Rust Programming Language

Steve Klabnik, Carol Nichols
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781491927274Errata PageSupplemental Content