Rust Tutorials: Expression vs Statement 🎯

beginner
17 min

Rust Tutorials: Expression vs Statement 🎯

Welcome to the Rust Expression vs Statement lesson! Let's explore two fundamental building blocks of Rust programming. This tutorial is designed for beginners and intermediates. 📝

Understanding Expressions and Statements 💡

In Rust, both expressions and statements can produce a result, but they are used differently.

Expressions 📝

Expressions in Rust are a series of operands and operators that return a value. They are usually used to compute values, assign values to variables, or as arguments in function calls.

Here's a simple example of an expression:

rust
let x = 1 + 2; // This expression computes the value 3 and assigns it to the variable x.

Statements 📝

Statements in Rust perform actions, but do not return a value. They are typically used to change the flow of control, like controlling loops, handling errors, or defining functions.

Here's a simple example of a statement:

rust
println!("Hello, World!"); // This statement prints "Hello, World!" to the console.

Differentiating Expressions and Statements 💡

To differentiate between expressions and statements, remember that expressions can be assigned to variables, while statements cannot.

rust
let result = 1 + 2; // This is an expression because the result can be assigned to a variable. let _; // This is a statement because it doesn't return a value and doesn't assign anything to a variable.

Quiz 💡

Quick Quiz
Question 1 of 1

Which of the following is an expression?

Wrapping Up 📝

Now that you understand the difference between expressions and statements, you can create more effective and efficient Rust code. By understanding these fundamental building blocks, you'll be well on your way to mastering Rust programming!

Stay tuned for more Rust tutorials on CodeYourCraft! 💡