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 ...
Get Programming Rust now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.