Create An Array Of String In Rust
Code snippet for how to Create An Array Of String In Rust with sample and detail explanation
Rust is a high-level programming language that provides a bevy of functionalities. This article will provide a guide on how to create an array of strings in Rust.
Code snippet for Creating an Array of Strings in Rust
Here’s a simple block of code which shows how to define an array of strings in Rust.
fn main() {
let array_of_strings: [&str; 3] = ["This", "is", "Rust"];
println!("{:?}", array_of_strings);
}
When you run this program, it should print ["This", "is", "Rust"]
.
Code Explanation for Creating an Array of Strings in Rust
To begin with, we declare our main function by typing fn main()
and then open a code block {
.
The function let
is used to create or define variables in Rust. An array in Rust is a data structure that stores elements of the same type. The code line let array_of_strings: [&str; 3] = ["This", "is", "Rust"];
is used to declare and initialize an array of strings with a fixed size of three.
The :&str
tells Rust that the data type for the elements of the array is string. The 3
in the square bracket after &str;
is used to specify the size of the array which is three in this case. ["This", "is", "Rust"]
initializes the array with the three strings.
The next line, println!("{:?}", array_of_strings);
prints out the contents of the array. println!
is a macro in Rust used for displaying output on the console. The {:?}
is used for formatting an array or other compound types. It prints the array as an inline sequence with commas separating the elements.
On running the code, it prints out ["This", "is", "Rust"]
and that, in a nutshell, is how you can create an array of strings in Rust.