Rust: Expressions

Rust 0.10

In the context of a programming language, an expression is something that can be evaluated and returns a value.


1 == 1

Is an expression that evaluates to the boolean value true.

In Rust many things are expressions; litterals, match (think pattern-matching), tuples, structs, if/else conditionals and loops are all expressions.

They will all return a value that can be used to initialize a variable or anywhere else where a value is needed.

The ; is used to suppress the return of the expression’s value and instead return (), which is known as the unit value.

Here are a couple of examples:

The first code block (delimited with brackets) will return the value of it’s last expression, inner * inner, which will be the value of the block expression itself (the whole block).

The value returned will be 4.

In the second case, the semicolon ;, symbol will suppress the value of the last statement and the value of the block expression will be ().

Here is another example:

This will print hello since the last value of the last expression in the function will be returned. Again this could be suppressed with a semicolon.

The return keyword could optionally have been used. return works as you would expect when placed anywhere within a function.

Finally here is an example of an if conditional acting as an expression:

In other languages you would have probably seen something like:

if (bool_value == true)
  int_value = 1;
 int_value = 0;

Here is the full code sample:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s