0
0
Rustprogramming~15 mins

Type inference in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Type inference
๐Ÿ“– Scenario: You are writing a small Rust program to calculate the total price of items in a shopping cart. Rust can often figure out the type of variables automatically, which is called type inference. This helps you write cleaner code without always specifying types.
๐ŸŽฏ Goal: Build a Rust program that uses type inference to calculate the total price of items in a cart and print the result.
๐Ÿ“‹ What You'll Learn
Create a variable called prices that holds a list of item prices as floating-point numbers.
Create a variable called total initialized to zero using type inference.
Use a for loop with variables price to iterate over prices and add each price to total.
Print the total price using println!.
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Type inference helps programmers write cleaner and shorter code without losing safety. It is used in many Rust programs to reduce clutter.
๐Ÿ’ผ Career
Understanding type inference is important for Rust developers to write efficient and readable code, which is valuable in software development jobs.
Progress0 / 4 steps
1
Create the list of prices
Create a variable called prices and set it to a list containing these floating-point numbers: 10.5, 20.0, and 5.75.
Rust
Need a hint?

Use let prices = vec![10.5, 20.0, 5.75]; to create a vector of floats.

2
Create a total variable with type inference
Add a variable called total and set it to 0.0 without specifying its type explicitly.
Rust
Need a hint?

Write let total = 0.0; and let Rust figure out the type.

3
Add prices to total using a for loop
Use a for loop with variable price to iterate over prices and add each price to total. Use let mut total to allow changing total.
Rust
Need a hint?

Make total mutable with mut and add each price inside the loop.

4
Print the total price
Use println! to print the text Total price: followed by the value of total.
Rust
Need a hint?

Use println!("Total price: {}", total); to show the result.