Hone logo
Hone
Problems

Rust Library Crate: A Simple Calculator

This challenge will guide you through creating your very first Rust library crate. You will implement a basic calculator that can perform arithmetic operations. This exercise is fundamental for understanding how to structure reusable code in Rust and how to manage dependencies within the Rust ecosystem.

Problem Description

Your task is to create a Rust library crate named simple_calculator. This library should expose functionality for performing basic arithmetic operations: addition, subtraction, multiplication, and division.

Key Requirements:

  • Functionality: Implement functions for add, subtract, multiply, and divide.
  • Data Types: All operations should handle floating-point numbers (f64).
  • Error Handling: The divide operation must gracefully handle division by zero, returning an appropriate error.
  • Public API: The functions should be publicly accessible from other crates that depend on simple_calculator.
  • Testing: Include unit tests for all implemented functions, covering both successful operations and error cases.

Expected Behavior:

  • add(a: f64, b: f64) -> f64: Returns the sum of a and b.
  • subtract(a: f64, b: f64) -> f64: Returns the difference between a and b.
  • multiply(a: f64, b: f64) -> f64: Returns the product of a and b.
  • divide(a: f64, b: f64) -> Result<f64, String>: Returns the quotient of a divided by b. If b is zero, it should return an Err with a descriptive error message (e.g., "Division by zero is not allowed.").

Examples

Example 1: Addition

use simple_calculator::add;

let result = add(5.5, 2.0);
// result should be 7.5

Example 2: Division with Zero

use simple_calculator::divide;

let result = divide(10.0, 0.0);
// result should be Err("Division by zero is not allowed.")

Example 3: Successful Division

use simple_calculator::divide;

let result = divide(10.0, 2.0);
// result should be Ok(5.0)

Constraints

  • The library must be a Rust crate.
  • Input numbers for operations will be of type f64.
  • The divide function must return a Result type to handle potential division by zero errors.
  • The crate must include comprehensive unit tests in a tests module.
  • The crate should be structured according to standard Rust library practices.

Notes

  • To create a new Rust library crate, use the command cargo new --lib simple_calculator.
  • Consider how to best represent errors for the divide function. The Result enum is the idiomatic way in Rust.
  • You'll need to make your functions pub so they can be used by external crates.
  • Place your unit tests within a #[cfg(test)] module in your lib.rs file.
  • Think about the edge cases for floating-point arithmetic, though for this basic calculator, standard f64 behavior is generally acceptable.
Loading editor...
rust