How to get the length of a string in Rust

In Rust, a string's length is determined by the amount of space it takes up in terms of UTF-8 encoded bytes. This is important because different characters can be encoded using different numbers of bytes. To clarify, when measuring the length of a string in Rust, we're looking at the count of UTF-8 bytes used to represent its characters.

Syntax

string.len()
Syntax for len method in Rust

Parameters

  • string: This is the string whose length we want to get.

Return value

The value returned is a number representing the length of the string specified.

Code

fn main() {
// create some strings
let str1 = "Edpresso";
let str2 = "Educative";
let str3 = "Rust";
let str4 = "Educative is the best platform!";
// print the length of the strings
println!("The length of {} is {}", str1, str1.len());
println!("The length of {} is {}", str2, str2.len());
println!("The length of {} is {}", str3, str3.len());
println!("The length of {} is {}", str4, str4.len());
}

Explanation

In the above code:

  • Lines 3–6: We create some string variables and initialize them.

  • Lines 9–12: We retrieve the length of each string with the len() method, and with the println!() method, we print the result to the console.