w3resource

Rust Function: String length

Rust Result and Option types: Exercise-6 with Solution

Write a Rust function that takes a string and returns Option representing the string length, returning None for empty strings.

Sample Solution:

Rust Code:

fn string_length(string: &str) -> Option<usize> {
    // Check if the input string is empty
    if string.is_empty() {
        // If the string is empty, return None
        None
    } else {
        // If the string is not empty, return Some with the length of the string
        Some(string.len())
    }
}

fn main() {
    // Test cases
    let empty_string = "";
    let non_empty_string = "Rust, world!";

    // Test the string_length function with an empty string
    match string_length(empty_string) {
        Some(length) => println!("Length of '{}' is {}", empty_string, length),
        None => println!("Empty string provided"),
    }

    // Test the string_length function with a non-empty string
    match string_length(non_empty_string) {
        Some(length) => println!("Length of '{}' is {}", non_empty_string, length),
        None => println!("Empty string provided"),
    }
}

Output:

Empty string provided
Length of 'Rust, world!' is 12

Explanation:

Here's a brief explanation of the above Rust code:

The function "string_length()" takes a string 'string' as input and returns an Option representing the length of the string if it's not empty. If the input string is empty, the function returns 'None'. The "main()" function provides test cases for both empty and non-empty strings to demonstrate the behavior of the "string_length()" function.

Rust Code Editor:

Previous: Rust Function: Date string parsing.
Next: Rust Function: Hex string to integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.