Skip to Content
Programming Rust, 2nd Edition
book

Programming Rust, 2nd Edition

by Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
June 2021
Intermediate to advanced
738 pages
18h 47m
English
O'Reilly Media, Inc.
Content preview from Programming Rust, 2nd Edition

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 and thus the majority of Rust code. Most things in Rust are expressions. In this chapter, we’ll explore the power this brings and how to work with its limitations. We’ll cover control flow, which in Rust is entirely expression-oriented, and how Rust’s foundational operators work in isolation and combination.

A few concepts that technically fall into this category, such as closures and iterators, are deep enough that we will dedicate a whole chapter to them later. 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 ...

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, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781492052586Errata PageSupplemental Content