Count A String Length In Rust
Code snippet for how to Count A String Length In Rust with sample and detail explanation
Rust, a systems programming language, not only offers memory safety but also has handy features for many tasks, including counting a string’s length. This article gives a brief guide on how to get the length of a string in Rust.
Code snippet: Counting String Length
Let’s start with the simple code snippet in Rust:
fn main() {
let my_string = String::from("Hello, Rust!");
println!("Length of my_string is: {}", my_string.len());
}
Just run this in your Rust environment and it would output:
Length of my_string is: 12
Code Explanation for Counting String Length
First, we define the function main()
, which is an entry point of any Rust program.
Inside the main function, this line of code:
let my_string = String::from("Hello, Rust!");
creates a string named “my_string” with an initial value of “Hello, Rust!“. We’re using Rust’s String::from
constructor here, which turns a string literal into a String
object.
Next, we calculate the length of the my_string
variable and print it as follows:
println!("Length of my_string is: {}", my_string.len());
The len()
method returns the length of a String, which is the number of bytes it contains. The println!()
macro prints the string to the console, replacing {}
with the variable provided after the comma; in this case, the length of my_string
.
The output will show the length of our string, which represents the number of bytes in it. Note that len()
doesn’t count characters, but bytes. Thus, if your string contains multibyte unicode characters, the reported length might be greater than you expect.
With this very simple line of Rust code, you can easily count the length of any provided string in Rust.