Comparing Multiple Rust Implementations of `string_to_number` with Shared Tests

⚓ Rust    📅 2025-12-20    👤 surdeus    👁️ 7      

surdeus

Overview

In this tutorial you’ll see several ways to convert a string slice (&str) into an i32, and how to test them all with one common test suite.

Rust’s built‑in testing support runs tests annotated with #[test] when you issue:

$ cargo test

This compiles and executes all your test functions. (Rust Documentation)


Implementations

In src/lib.rs define multiple variants:

// 1) FromStr explicitly
fn string_to_number_fromstr(s: &str) -> i32 {
    use std::str::FromStr;
    i32::from_str(s).unwrap()
}

// 2) Using `parse()`
fn string_to_number_parse(s: &str) -> i32 {
    s.parse::<i32>().unwrap()
}

// 3) Manual digit processing
fn string_to_number_manual(s: &str) -> i32 {
    let mut result = 0i32;
    let mut negative = false;
    for (i, c) in s.chars().enumerate() {
        if i == 0 && c == '-' {
            negative = true;
            continue;
        }
        result = result * 10 + (c as i32 - '0' as i32);
    }
    if negative { -result } else { result }
}

Common Test Runner

Below the functions, define one test‑helper that runs a set of assertions:

fn run_string_to_number_tests(f: fn(&str) -> i32) {
    assert_eq!(f("1234"), 1234);
    assert_eq!(f("605"), 605);
    assert_eq!(f("1405"), 1405);
    assert_eq!(f("-7"), -7);
}

Call Shared Tests for Each Variant

Finally, wrap test cases in a #[cfg(test)] block:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fromstr() {
        run_string_to_number_tests(string_to_number_fromstr);
    }

    #[test]
    fn test_parse() {
        run_string_to_number_tests(string_to_number_parse);
    }

    #[test]
    fn test_manual() {
        run_string_to_number_tests(string_to_number_manual);
    }
}

All annotated test functions (#[test]) will run when invoked by cargo test. (Rust Programming Language)


Linux Commands

Below are the essential commands you’ll run in a terminal:

1. Create a new Cargo library (if you don’t have one yet)

$ cargo new string_to_number_lib --lib
$ cd string_to_number_lib

2. Write code

Edit src/lib.rs with the implementations and tests shown above.

3. Compile & test

Run all tests:

$ cargo test

To run only specific tests, you can filter by name:

$ cargo test parse

Summary

  • You define several variants of string_to_number in Rust.
  • You reuse a single test suite (run_string_to_number_tests) for all variants.
  • You run tests using cargo test, which compiles and executes your annotated test functions. (Rust Documentation)

1 post - 1 participant

Read full topic

🏷️ Rust_feed