get length of string rust

To get the length of a string in Rust, you can use the len() method. Here's an example:

fn main() {
    let my_string = String::from("Hello, Rust!");
    let length = my_string.len();
    println!("Length of the string: {}", length);
}

This code creates a String called my_string and assigns it the value "Hello, Rust!". The len() method is then used to get the length of the string, and the result is printed to the console using println!(). In this example, the output would be:

Length of the string: 13

The len() method returns the number of bytes in the string, not the number of characters. If you want to get the number of characters, you can use the chars() method and then call count() on the iterator. Here's an example:

fn main() {
    let my_string = String::from("Hello, Rust!");
    let length = my_string.chars().count();
    println!("Length of the string: {}", length);
}

This code creates the same String as before and then uses the chars() method to get an iterator over the string's characters. The count() method is then called on the iterator to get the number of characters in the string. The output would be the same as before:

Length of the string: 13

I hope this helps! Let me know if you have any further questions.