How to Compare Strings with Different Encodings in Rust

Convert strings to UTF-8 using std::str::from_utf8 or encoding_rs before comparing with the == operator.

Convert both strings to the same encoding, typically UTF-8, before comparing them using the == operator. Rust's String type is UTF-8 by default, so you must decode non-UTF-8 byte slices into String or &str first.

fn main() {
    let utf8_bytes = b"Hello";
    let latin1_bytes = b"H\xc3\xa9llo"; // UTF-8 encoded "Héllo"

    let s1 = std::str::from_utf8(utf8_bytes).unwrap();
    let s2 = std::str::from_utf8(latin1_bytes).unwrap();

    println!("Are they equal? {}", s1 == s2);
}

If your data is in a different encoding like Latin-1, use the encoding_rs crate to decode it into a String before comparison.