avatarAnkit Tanna

Summary

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3473

Abstract

ute the statements when running a program. There is some sense of strictness that Rust imposes which we can have a look at the below code snippet:</p><div id="6579"><pre><span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() { <span class="hljs-keyword">let</span> <span class="hljs-variable">cats</span> = <span class="hljs-number">1050</span>;

<span class="hljs-keyword">if</span> cats &gt; <span class="hljs-number">1</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Multiple cats!"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> cats == <span class="hljs-number">0</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No cats!"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Need more cats"</span>);
}

}</pre></div><h2 id="627e">Observations from the above code:</h2><ol><li>Conditionals <code>cats > 1</code> don’t need the parenthesis <code>()</code>. Compiler throws the error if you use <code>()</code></li><li>On the contrary to other programming languages, you do need the curly braces <code>{}</code>. They are mandatory. Compiler throws an error if you don’t use <code>{}</code></li><li>The conditional expression <code>cats > 1</code> has to be a <code>boolean</code> and cannot be a truthy or falsy value. It has to be a <code>true</code> or <code>false</code> value.</li></ol><h2 id="cf33">Statements vs Expressions</h2><p id="a6cf">There is a noticeable difference between statements and expressions in Rust. Statements have a semi-colon <code>;</code> at the end where as expressions don’t have a semi-colon <code>;</code> at the end.</p><p id="b297">An <b>expression </b>in Rust is something that evaluates to a value. <code>cats > 1000</code> is an expression. In fact <code>cats</code> is an expression and <code>1000</code> is an expression.</p><figure id="6bcf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*BR2lkYL82xgsMjSFRvGeeQ.png"><figcaption>Examples of expressions</figcaption></figure><p id="e5f2">All the highlighted lines above are expressions.</p><p id="d38d">Notice that expressions don’t have semi-colons at the end.</p><p id="2808">A <b>statement</b> on the other hand does not evaluate to a value.</p><div id="ecf4"><pre><span class="hljs-built_in">println!</span>(<span class="hljs-string">"Multiple cats!"</span>);</pre></div><p id="bd9b">Above statement does not evaluate a value. It also has semi-colon <code>;</code> at the end which is a clue that it is a statement.</p><p id="b120">Why does this difference of having a semi-colon or not matter? Rust compiler gives you little conveniences when chosing expression over statements. Take a look at below snippet:</p><div id="802d"><pre><span class="hljs-keyword">fn</span> <span class="hljs-title function_">multiply_both</span>(x: <span class="hljs-type">f64</span>, y: <span class="hljs-type">f64</span>) <span class="hljs-punctuation">-></span> <span class="hljs-type">f64</span> { <span class="hljs-keyword">return</span> xy; }</pre></div><p id="19b7"><code>xy</code> is an expression</p><p id="e2a0"><code>return x*y;</code> is a statement.</p><figure id="6f69"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*i_V5A6EIioXs6TBgo5IJaQ.png"><figcaption>Expression vs Statement

Options

</figcaption></figure><p id="ddd7">In language like JavaScript, you need <code>return</code> keyword. But in Rust, you can also replace above snippet using below snippet:</p><div id="7262"><pre><span class="hljs-keyword">fn</span> <span class="hljs-title function_">multiply_both</span>(x: <span class="hljs-type">f64</span>, y: <span class="hljs-type">f64</span>) <span class="hljs-punctuation">-&gt;</span> <span class="hljs-type">f64</span> { x*y }</pre></div><p id="0da8">You can avoid <code>return</code> keyword if the last statement in the function is an expression, i.e. without <code>;</code>. The compiler simply infers that you want to return the value. If a function ends with an expression, it automatically returns that expression.</p><p id="0c9f">Below snippet will throw a compiler error as it does not return any value:</p><div id="5d06"><pre><span class="hljs-keyword">fn</span> <span class="hljs-title function_">multiply_both</span>(x: <span class="hljs-type">f64</span>, y: <span class="hljs-type">f64</span>) <span class="hljs-punctuation">-&gt;</span> <span class="hljs-type">f64</span> { x*y; }</pre></div><p id="2bca">as <code>x*y;</code> is a statement and no longer an expression.</p><p id="fc3c">So we can have ternary <code>if</code> written as below:</p><div id="936d"><pre><span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() { <span class="hljs-keyword">let</span> <span class="hljs-variable">message</span> = <span class="hljs-keyword">if</span> cats &gt; <span class="hljs-number">1</span> { <span class="hljs-string">"Multiple cats!"</span> } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> cats == <span class="hljs-number">0</span> { <span class="hljs-string">"No cats!"</span> } <span class="hljs-keyword">else</span> { <span class="hljs-string">"Need more cats"</span> }; }</pre></div><p id="7a98">Notice the <code>;</code> at the end of the entire <code>if</code> block. It is mandatory.</p><p id="fe8b">In cases of automatic returns (i.e. functions without <code>return</code> keyword), the last expression would be automatically returned. Above that expression, there should be only statements, i.e. ending with <code>;</code>.</p><p id="f5d2">If you are trying to make an early return from the function, you do need to specify the <code>return</code> keyword.</p><p id="c290">I hope you enjoyed this article with the details about Booleans, Conditionals, Statements and Expressions. Please share your feedback in the comments.</p><p id="0fec">You can subscribe to my newsletter about <b>The Rust Programming Language <a href="https://tinyletter.com/ankittanna"></a></b><a href="https://tinyletter.com/ankittanna">here</a>. You can read about all the articles in this series <a href="https://readmedium.com/the-rust-programming-language-4b22bc717ecc">here</a>.</p><h2 id="2a08">Rustaceans 🚀</h2><p id="7052">Thank you for being a part of the Rustaceans community! Before you go:</p><ul><li>Show your appreciation with a clap and follow the publication</li><li>Discover how you can contribute your own insights to <a href="https://readmedium.com/rustaceans-submissions-are-now-open-924e67cc595d"><b><i>Rustaceans</i></b></a>.</li><li>Connect with us: <a href="https://twitter.com/rustaceans_rs"><b><i>X</i></b></a> | <a href="https://substack.com/@weeklyrust"><b><i>Weekly Rust Newsletter</i></b></a></li></ul></article></body>
The Rust Programming Language

The Rust Programming Language — Primitives — Booleans, Conditionals, Statements and Expressions

In this article, we are going to learn about subtle nuances of The Rust Programming Language when using Booleans, Conditionals, Statements and Expressions. We’ll also get to learn that Rust omits some of the features from other languages intentionally.

Booleans:

Let us start with Booleans. As all the other languages, we only have true and false. Look at the below code snippet:

fn main() {
    let should_go_fast = true;
    let should_go_slow = false;

    println!("should_go_fast {}", should_go_fast);
    println!("should_go_slow {}", should_go_slow);
}

You can also cast the booleans to u8 and the output would be 1 for true and 0 for false. Look at the below code snippet:

fn main() {
    let should_go_fast = true;
    let should_go_slow = false;

    println!("should_go_fast as u8 {}", should_go_fast as u8);
    println!("should_go_slow as u8 {}", should_go_slow as u8);
}

Double Equals == :

There is only == in Rust. But there is no === in Rust. What == does is it structurally compares the Left hand side expressions and Right hand side expressions. Rust does not have referential equality. If you use == it means Rust will go deeply into an object and compare each and every value and return you true or false. Hence, with == only in the programming language, Rust omits the need of ===. So, == is the deep equality in Rust. Look at the below code snippet:

fn main() {
  pritln!("{}", 1==2);
}

Conditionals:

Rust has if which allows you to conditionally execute the statements when running a program. There is some sense of strictness that Rust imposes which we can have a look at the below code snippet:

fn main() {
    let cats = 1050;

    if cats > 1 {
        println!("Multiple cats!");
    } else if cats == 0 {
        println!("No cats!");
    } else {
        println!("Need more cats");
    }
}

Observations from the above code:

  1. Conditionals cats > 1 don’t need the parenthesis (). Compiler throws the error if you use ()
  2. On the contrary to other programming languages, you do need the curly braces {}. They are mandatory. Compiler throws an error if you don’t use {}
  3. The conditional expression cats > 1 has to be a boolean and cannot be a truthy or falsy value. It has to be a true or false value.

Statements vs Expressions

There is a noticeable difference between statements and expressions in Rust. Statements have a semi-colon ; at the end where as expressions don’t have a semi-colon ; at the end.

An expression in Rust is something that evaluates to a value. cats > 1000 is an expression. In fact cats is an expression and 1000 is an expression.

Examples of expressions

All the highlighted lines above are expressions.

Notice that expressions don’t have semi-colons at the end.

A statement on the other hand does not evaluate to a value.

println!("Multiple cats!");

Above statement does not evaluate a value. It also has semi-colon ; at the end which is a clue that it is a statement.

Why does this difference of having a semi-colon or not matter? Rust compiler gives you little conveniences when chosing expression over statements. Take a look at below snippet:

fn multiply_both(x: f64, y: f64) -> f64 {
  return x*y;
}

x*y is an expression

return x*y; is a statement.

Expression vs Statement

In language like JavaScript, you need return keyword. But in Rust, you can also replace above snippet using below snippet:

fn multiply_both(x: f64, y: f64) -> f64 {
  x*y
}

You can avoid return keyword if the last statement in the function is an expression, i.e. without ;. The compiler simply infers that you want to return the value. If a function ends with an expression, it automatically returns that expression.

Below snippet will throw a compiler error as it does not return any value:

fn multiply_both(x: f64, y: f64) -> f64 {
  x*y;
}

as x*y; is a statement and no longer an expression.

So we can have ternary if written as below:

fn main() {
    let message = if cats > 1 {
        "Multiple cats!"
    } else if cats == 0 {
        "No cats!"
    } else {
        "Need more cats"
    };
}

Notice the ; at the end of the entire if block. It is mandatory.

In cases of automatic returns (i.e. functions without return keyword), the last expression would be automatically returned. Above that expression, there should be only statements, i.e. ending with ;.

If you are trying to make an early return from the function, you do need to specify the return keyword.

I hope you enjoyed this article with the details about Booleans, Conditionals, Statements and Expressions. Please share your feedback in the comments.

You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.

Rustaceans 🚀

Thank you for being a part of the Rustaceans community! Before you go:

  • Show your appreciation with a clap and follow the publication
  • Discover how you can contribute your own insights to Rustaceans.
  • Connect with us: X | Weekly Rust Newsletter
Rust
Rust Programming Language
Rustlang
Programming Languages
Webassembly
Recommended from ReadMedium