OneBite.Dev - Coding blog in a bite size

Compare Two Strings In Rust

Code snippet for how to Compare Two Strings In Rust with sample and detail explanation

Rust, as a strongly typed, memory-safe, and concurrent programming language, is increasingly becoming a popular choice among developers. Today we will delve into a simple yet fundamental topic in programming - comparing two strings in Rust.

Code snippet for Comparing Strings

fn main() {
    let str1 = "Hello, world!".to_string();
    let str2 = "Hello, world!".to_string();

    if str1 == str2 {
        println!("The two strings are equal.");
    } else {
        println!("The two strings are not equal.");
    }
}

Code Explanation for Comparing Strings

In the code snippet above, we start by declaring a main function which is the entry point of every Rust program with fn main().

We declare and initialise two variables, str1 and str2, with the let keyword which is Rust’s way of creating a variable. These variables are both given the value of “Hello, world!“. The to_string() function is used to convert the literals into string types so they can be compared.

To compare if these two strings are identical, we use an if statement. The == sign is the equality operator that checks if the string in str1 and str2 are the same.

If they are equal, the block of code under the if statement will execute and The two strings are equal. will be printed.

If they are not equal, the block of code under the else statement will execute and The two strings are not equal. will be printed.

It’s important to note that this comparison is case sensitive, a string “Hello” is not the same as “hello”. If case insensitivity is preferred, both strings will need to be converted to either all upper or lower case before the comparison. Running this code will output The two strings are equal. as str1 and str2 both have “Hello, world!” as their values.

With Rust’s simplicity and efficiency, string comparison is just as easy and intuitive as it is in any other language.

rust