Programming A Guessing Game Flashcards
What is the command to create a new Rust project?
cargo new project_name
cd project_name
What is the io library?
input/output
Where does the io library come from?
The standard library known as std
Example: use std::io;
What is the prelude?
The prelude is the list of things that Rust automatically imports into every Rust program. It’s kept as small as possible, and is focused on things, particularly traits, which are used in almost every single Rust program.
More info in the standard library documentation:
https://doc.rust-lang.org/std/prelude/index.html
How do you use a type that isn’t in the prelude?
You must bring the type into scope explicitly with a use statement.
Using the std::io library provides you with a number useful features, including the ability to accept user input.
fn main() {
The main function is the entry point into the program.
What do each of these mean?
fn
main()
{
The fn syntax declares a new function.
The parentheses, (), indicate there are no parameters.
The curly bracket, {, starts the body of the function.
How do you make a variable mutable?
Add mut before the variable’s name.
let apples = 5; // immutable let mut bananas = 5; // mutable
let mut guess will introduce a mutable variable named what?
The mutable variable will be named guess.
What does the = sign mean?
It tells Rust we want to bind something to the variable now.
let mut guess = String::new();
String::new is bound to guess. What is String:new?
It is a function that returns a new instance of a String.
String is a string type provided by the standard library that is a growable, UTF-8 encoded bit of text.
https://doc.rust-lang.org/std/string/struct.String.html
let mut guess = String::new();
What does the :: syntax in the ::new line indicate?
The :: syntax in the ::new line indicates that new is an associated function of the String type.
An associated function is a function that’s implemented on a type, in this case String. This new function creates a new, empty string.
What is an associated function?
An associated function is a function that’s implemented on a type.
let mut guess = String::new();
What does this code create?
In full, the let mut guess = String::new(); line has created a mutable variable that is currently bound to a new, empty instance of a String.
We’ll call the stdin function from the io module.
io::stdin()
.read_line(&mut guess)
What does this allow us to do?
It will allow us to handle user input.
io::stdin()
.read_line(&mut guess)
If we hadn’t imported the io library with use std::io at the beginning of the program, how else could we still use the function?
We could write the function call as std::io:stdin.
The stdin function returns an instance of std::io::Stdin, which is a type that represents a handle to the standard input for your terminal.