CodeNewbie Community

Jeff Mitchell
Jeff Mitchell

Posted on

A Rust tip calculator

I'm trying my best to work systematically through the Rust Book but I find it difficult to just read about programming without actually doing something. Inevitably, my mind wanders and I tune out.

Enter the book, "Exercises for Programmers: 57 Challenges to Develop Your Coding Skills", by Brian P. Hogan. This book contains a series of open ended challenges which nicely give an objective to practice on.

The introductory challenge was to code a tip calculator. Here is my solution using Rust:

// Tip Calculator

use std::io;

fn main() {

    println!("What is the amount of your bill (in dollars)?");

    let mut bill_amount = String::new();

        .read_line(&mut bill_amount)
        .expect("Failed to read line");

    let bill_amount: f32 = bill_amount.trim().parse().expect("Please type a number!");

    println!("What is the tip rate (percent)?");

    let mut tip_rate = String::new();

        .read_line(&mut tip_rate)
        .expect("Failed to read line");

    let tip_rate: f32 = tip_rate.trim().parse().expect("Please type a number!");

    let tip: f32 = calc_tip(bill_amount.abs(), tip_rate.abs());   // get rid of a negative bill amount value by using abs(), if the user accidentally entered a negative value

    let total: f32 = total_amount(bill_amount.abs(), tip);          // get rid of a negative tip rate value by using abs(), if the user accidentally entered a negative value

    println!("The bill amount is: ${}", bill_amount);
    println!("The tip rate is: {:.2}%", tip_rate);      // round output to 2 decimal places

    println!("The tip is: ${:.2}", tip);
    println!("The total is: ${:.2}", total);            // round output to 2 decimal places

fn calc_tip(bill_amount: f32, tip_rate: f32) -> f32 {
    bill_amount * (tip_rate / 100.0) 

fn total_amount(bill_amount: f32, tip: f32) -> f32 {
    bill_amount + tip
Enter fullscreen mode Exit fullscreen mode

My tip calculator asks the user for the value of their bill and the tip rate. It outputs the value of the tip and the total amount of the final bill.

This is a nothing little piece of code which will not win any awards, but it helped me cement a few basic concepts in Rust, namely:

  1. variables in rust are immutable by default and you must explicitly choose to make them mutable with the mut keyword

  2. variables can be shadowed, which enables transformations between different data types

  3. if you want a function to return a value, omit the semicolon such that such that your code is an expression, which inherently returns a value.

I feel I'm getting to grips with the most basic building blocks of Rust. It's not that different in concept from the languages of yore that I learned on. Creating very basic, but still useful, little command line programs seems fairly straightforward.

Discussion (0)