Storing Strings in an Array
Learn how to use basic functionalities of Rust like storing and searching data in an array.
We'll cover the following...
Our treehouse is an exclusive club. Only individuals on the approved list of friends are allowed inside. We could accomplish this with if
statements. If we only want to admit our friend, Bert, we could use the following code:
if your_name == "bert" {println!("Welcome.");}else{println!("Sorry, you are not on the list.");}
The if/else
control flow system works much like it does in other programming languages: if the condition is true
, then it executes the code in the first block. Otherwise, it runs the code in the else block.
When we do our comparison, we need to make sure that we compare our string with “bert”
in lower case. We use lowercase because the input function converts the user’s input to lowercase, so we need to compare with lower case strings for there to be a match.
If we have a second friend named Steve, we could allow them inside by using an or expression. The OR operation in Rust is expressed with ||
:
if your_name == "bert" || your_name == "steve"
Combining ...