Rusty

Expression vs Statement in Rust

Let’s see the difference between them via example.

Image for post
Image for post
Photo by Joel Naren on Unsplash

Expression

An expression may have two roles: it always produces a value, and it may have effects (otherwise known as “side effects”). An expression evaluates to a value, and has effects during evaluation. Many expressions contain sub-expressions (operands). The meaning of each kind of expression dictates several things:

  • Whether or not to evaluate the sub-expressions when evaluating the expression
  • The order in which to evaluate the sub-expressions
  • How to combine the sub-expressions’ values to obtain the value of the expression

In this way, the structure of expressions dictates the structure of execution. Blocks are just another kind of expression, so blocks, statements, expressions, and blocks again can recursively nest inside each other to an arbitrary depth.

This is an expression with “x+1” without the semi-colon “;”.

Statement

A statement is a component of a block, which is in turn a component of an outer expression or function.

Rust has two kinds of statement: declaration statements and expression statements.

x+1;

This is a statement.

~~~Happy coding~~~

Written by

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store