- Make a new project named
variablesusing cargo- See "cargo help" if you forgot the command.
- Open
Cargo.toml- Change the version number to
2.3.4and save the file. Keep an eye out for that version number in cargo's output when you run it!
- Change the version number to
- In
src/main.rsat the start of themain()function:- Declare the variable
missilesand initialize it to8 - Declare the variable
readyand initialize it to2
- Declare the variable
- Change the
println!(...)at the end ofmain()to:println!("Firing {} of my {} missiles...", ready, missiles);
- Run your program using cargo (see "cargo help" if you forgot the command).
Some common errors you may hit:
- Forgot to use
letto bind a variable - Forgot a semicolon
;at the end of a line
- Forgot to use
- After the
println!(...), subtractreadyfrommissileslike this:missiles = missiles - ready;
- Add a second
println!(...)to the end:println!("{} missiles left", missiles);
- Run your program again using cargo
- Did you run into an error about mutability? Go back and add
mutat the right spot on the line where you declaremissiles.
- Did you run into an error about mutability? Go back and add
- Declare a constant named
STARTING_MISSILESand set it to8(the type isi32). - Declare a constant named
READY_AMOUNTand set it to2(alsoi32). - Use the constants to initialize
missilesandready- Where did you put the constants? If you put them inside the
main()function, try moving them up abovemain()to module scope!
- Where did you put the constants? If you put them inside the
- Nice. Congratulate yourself on a job well done! You are a Rust programmer now!
- Explicitly annotate the variables with the type
i32 - Try binding the variables all at once on one line using a pattern (parentheses and commas) -- can you figure out where
mutgoes?- Can you figure out the correct type annotation when you assign them all in one line? Hint: it will use the same sort of pattern as the variables and values.
- Instead of changing missiles, use the value
missiles - readydirectly in the secondprintln!(...)- What warning does cargo emit when you run your program now? Can you fix it?
- Add another variable to your program but don't use it.
- What does cargo say when you run your program?
- Try modifying a constant in
main()(for example,READY_AMOUNT = 1). What does the error look like?