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, anddivide. - Data Types: All operations should handle floating-point numbers (
f64). - Error Handling: The
divideoperation 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 ofaandb.subtract(a: f64, b: f64) -> f64: Returns the difference betweenaandb.multiply(a: f64, b: f64) -> f64: Returns the product ofaandb.divide(a: f64, b: f64) -> Result<f64, String>: Returns the quotient ofadivided byb. Ifbis zero, it should return anErrwith 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
dividefunction must return aResulttype to handle potential division by zero errors. - The crate must include comprehensive unit tests in a
testsmodule. - 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
dividefunction. TheResultenum is the idiomatic way in Rust. - You'll need to make your functions
pubso they can be used by external crates. - Place your unit tests within a
#[cfg(test)]module in yourlib.rsfile. - Think about the edge cases for floating-point arithmetic, though for this basic calculator, standard
f64behavior is generally acceptable.