0
0
Rustprogramming~10 mins

Using if as expression in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign the correct value using if as an expression.

Rust
let number = 5;
let result = if number > 0 [1] "positive" else "non-positive";
println!("{}", result);
Drag options to blanks, or click blank then click option'
A{
B==
C>
D;
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using comparison operators like '==' instead of starting a block.
Ending the line with a semicolon which would make the expression unit type.
2fill in blank
medium

Complete the code to assign the correct string based on the value of score using if as an expression.

Rust
let score = 85;
let grade = if score >= 90 [1] "A" else "B";
println!("Grade: {}", grade);
Drag options to blanks, or click blank then click option'
A{
B;
C==
D>
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a semicolon after the condition which ends the expression.
Using comparison operators instead of starting a block.
3fill in blank
hard

Fix the error in the code by completing the if expression correctly.

Rust
let x = 10;
let y = if x < 5 [1] 1 else 2;
println!("{}", y);
Drag options to blanks, or click blank then click option'
A==
B;
C{
D:
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a semicolon after the condition which ends the expression.
Using comparison operators instead of braces.
4fill in blank
hard

Complete the code to create a dictionary comprehension that uses if as an expression.

Rust
let words = ["apple", "bee", "cat"];
let lengths = words.iter().map(|word| (word, word.len() { 3 {BLANK_2}} "long" else "short")).collect::<Vec<_>>();
Drag options to blanks, or click blank then click option'
A>
B<
C{
D;
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Not using curly braces for the if expression.
Using the wrong comparison operator.
5fill in blank
hard

Fill all three blanks to assign a value using nested if expressions.

Rust
let num = 7;
let description = if num [1] 0 [2] "positive" else if num [3] 0 {"negative"} else {"zero"};
Drag options to blanks, or click blank then click option'
A>
B<
C==
D>=
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using wrong comparison operators that do not cover all cases.
Missing braces for the nested if expression.