-
Book Overview & Buying
-
Table Of Contents
Rust for C++ Developers
By :
In our programs, we often want to take different paths through the code based on the state of the program. Conditional execution and looping are collectively called control flow and are essential to understanding all but the simplest of programs.
The most straightforward form of control flow is the simple if statement, and we'll find that, in Rust, it shares many similarities with C++. Let's imagine that we are computing an average and want to guard against a divide-by-zero operation:
simple_if_statement.rs
let mut avg = 0;
if count != 0 {
avg = sum / count;
}
simple_if_statement.cpp
int avg = 0;
if (count != 0) {
avg = sum / count;
}
In Rust, we see that parentheses are not syntactically required for an if statement, and we'll find that this is true for all other control flow statements as well. This saves a little typing, but it also, thankfully, preempts a lot of arguing about how exactly...