Introduction
In this lab, we learn about using if
-else
statements in Rust. Similar to other programming languages, if
-else
statements in Rust don't require parentheses around the condition and each condition is followed by a block of code. These conditionals are expressions, so all branches must return the same type. Within the code example provided, we first check if the variable n
is less than 0, and if so, it prints that n
is negative. If n
is not less than 0, we then check if it is greater than 0 and print that n
is positive. Finally, if none of the previous conditions are met, we print that n
is zero. Another example demonstrates how the if
-else
statement can be used as an expression to assign a new value to the variable big_n
. If n
is between -10 and 10, it prints that n
is a small number and assigns 10 * n
to big_n
. Otherwise, it prints that n
is a big number and assigns n / 2
to big_n
. The final output of n
and big_n
is printed at the end.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs
, compile and run it with rustc main.rs && ./main
.
Skills Graph
%%%%{init: {'theme':'neutral'}}%%%%
flowchart RL
rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"])
rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"])
rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"])
rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"])
rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"])
rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`")
rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`")
rust/DataTypesGroup -.-> rust/type_casting("`Type Conversion and Casting`")
rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`")
rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`")
rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`")
rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`")
subgraph Lab Skills
rust/variable_declarations -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/integer_types -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/type_casting -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/function_syntax -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/expressions_statements -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/lifetime_specifiers -.-> lab-99303{{"`Conditional Statements in Rust`"}}
rust/operator_overloading -.-> lab-99303{{"`Conditional Statements in Rust`"}}
end