OneBite.Dev - Coding blog in a bite size

Check If A String Is Empty In Rust

Code snippet for how to Check If A String Is Empty In Rust with sample and detail explanation

Handling strings is a key part of any coding language, including Rust. One task that often comes up is checking whether a string is empty or not. This process is straightforward in Rust, as this article will demonstrate.

Code snippet to check if a string is Empty In Rust

fn main() {
    let string1 = String::from("");
    let string2 = "Hello, Rust!".to_string();

    println!("String 1 is empty: {}", string1.is_empty());
    println!("String 2 is empty: {}", string2.is_empty());
}

Code Explanation for Checking if a String is Empty In Rust

In the code snippet above, we have two strings: string1 which is an empty string, and string2 which is a non-empty string.

  1. We first declare string1 and string2 using the let keyword.
    let string1 = String::from("");
    let string2 = "Hello, Rust!".to_string();

In Rust, you can create a new string in two ways, either by using String::from("") or "Hello, Rust!".to_string(). Both ways are equivalent.

  1. After that, we check if each string is empty using Rust’s built-in is_empty() method.
    println!("String 1 is empty: {}", string1.is_empty());
    println!("String 2 is empty: {}", string2.is_empty());

The is_empty() function is a method that performs an equality operation comparing the length of the string with zero and returns a Boolean value (Either true or false). If the string length is zero, then it returns true, proving that the string is empty. If the string length is not zero, then it returns false, indicating that the string is not empty.

The println! macro then prints the result of the is_empty() check to the terminal.

In our case, for string1 it returns true as the string is empty, whereas, for string2, it returns false as the string contains text.

That’s how you can effectively check if a string is empty or not in Rust.

rust