In today's studio you will set up the development environment you'll be using throughout this semester, make sure everything is working, and explore how to create, build, and run Rust programs in that environment. You will also explore how different kinds of errors can be handled in Rust, and how both language-level and library-level semantics for error handling act to preserve safety of programs. Finally, you will explore how variable declarations are managed at different scopes of a Rust crate, including public, private, const, static, and atomic variables, and how namespaces introduced by modules affect scoping and access.
Throughout the semester, we will use the 1.71.0 versions of the Rust compiler (rustc), compilation and package manager (cargo), and documentation tool (rustdoc).
Please complete the following required exercises, and as many of the optional enrichment exercises as you would like to try. I encourage you to please work in groups of 2 or 3 people on each studio (and the groups are allowed to change from studio to studio) though if you would prefer to complete any studio by yourself that is also allowed.
As you work through these exercises, please record your answers, and when you finish them please log into Canvas, select this course in this semester, and then on the Canvas page for this studio assignment upload (1) a file containing your answers and (2) any code you produced while answering the exercises. Only one submission per team, please, and if you need to re-submit it the person who originally submitted the studio should please be the one to do that.
Make sure that the name of each person who worked on these exercises is listed in the first answer, and make sure you number each of your responses so it is easy to match your responses with each exercise.
As the answer to the first exercise, list the names of the people who worked together on this studio.
Log in using ssh into shell.cec.wustl.edu using your WUSTL
Key id and password. On a Mac or Linux computer, you can just run ssh
directly from within a terminal window. On many versions of Windows,
you can run ssh directly from the command prompt. If the command is
not recognized, you will need to install and use an SSH client, such as
PuTTY or
WinSCP.
Be careful! When you connect with ssh, you should specify your username, e.g.
ssh username@shell.cec.wustl.edu
or you may risk getting locked out of the server if the default username isn't the same as your WUSTL Key
username
(e.g., on a Raspberry Pi if you took CSE 422S).
If you connect with the wrong username or password 5 times in 30 minutes,
your IP address may be blocked.
To help prevent lockouts due to incorrect password attempts, you may want to log in using an SSH key instead of a password, as detailed on the ssh_key_generation.html page.
Because compiles may be computationally intensive (especially for longer lab assignments later in the
semester), you should not run them on the shell.cec.wustl.edu server, and instead you should run:
qlogin
which will log you into a dedicated Linux host machine. Optionally, if you'd like to
use more than one processor core, you can specify that, as in:
qlogin -c 2
which will request 2 cores instead of the default of 1.
As the answer to this exercise, write down the hostname of the linuxlab machine you're using, which you can
find out at any time by issuing the command hostname if you didn't write it down immediately when
you logged in.
You will now set up your environment to use the 1.71.0 versions of the Rust compiler (rustc), compilation and package manager (cargo), and documentation tool (rustdoc), by issuing the following command:
module add rust-2023
Note: You should please also add the following at the end of the file ~/.bashrc
(which you may need to update if it differs from the one you had prior to the home directory changes on the
Linux Lab cluster - the previous version can be found at /home/warehouse/{washukey}/.bashrc where
{washukey} is your WUSTL Key login id):
if [[ $SLURM_JOB_ACCOUNT == *"class"* ]]; then
module add rust-2023
fi
To confirm that your environment is using the correct versions of the Rust tools, please issue the following commands:
rustc --version
and then
cargo --version
and then
rustdoc --version
and as the answer to this exercise please show the output that each of them produced, and confirm that they each output the correct version number.
You may decide to start, switch, or stop using AI tools at any time. As the answer to this excercise, please write down which options you selected.
You should now create a directory where you will keep your code for this course this semester (named something
like e.g., cse5402) and cd into that directory and in it create a directory for this
studio and cd into it.
In that top-level directory for this studio, issue the command cargo new hello, which should
create a new package in a directory named hello.
Issue the commands cat hello/Cargo.toml and then cat hello/src/main.rs to print out
the metadata and source code for the package respectively, and as the answer to this exercise please show the
output those commands produced.
Compile and run the program by issuing the commands cd hello and
then cargo run, and as the answer to this exercise please show the
output that was produced. Congratulations, you are now officially a
Rustacean!
The program that was generated for you automatically simply prints out
a message to the standard output stream, and ignores any command line
arguments that may have been passed to it. Use the cd command
to return to the top-level directory for this studio (the one that contains the
hello directory), and in it issue the command
cargo new cmdargs to create a new package for a program that
will iterate through and print out the command line arguments it was given
or if none were given will print out a helpful usage message showing how
to run it.
Change into the cmdargs/src directory and edit the
main.rs file that it contains.
Above the main function, add the declaration use std::env; and
modify the main function so that it (1) uses a for loop and the iterator
returned by the std::env module's args function
to push all the strings
in the command line with which the program was run (including the name of the
program itself) into a vector, (2) checks the length of the vector and if
there is only a single element in the vector (which is the program name)
(3a) prints a line with a helpful usage message that contains the program name,
or otherwise (3b) prints out the
program name and lists the command line arguments that it was run with. The
usage message should look something like the following
usage: ./cmdargs <arg1> [<arg2> ...]
and otherwise the program should output something like
arguments passed to ./cmdargs were ["foo", "baz"]
Compile and run your program with command line arguments and without command line arguments, and as the answer to this exercise please show the code you wrote and the output the program produced when run with vs. without command line arguments.
In this exercise and the next one, we will consider alternative approaches
to having the executable program return a non-zero exit code, whenever it
issues the usage message. Above the main function, add the declaration
use std::process::ExitCode; and then declare an unigned integer
constant for the non-zero exit code as in:
const BAD_ARGS: u8 = 1;
Modify the main function's signature
so that its return type is ExitCode, as in
fn main() -> ExitCode {
instead of simply fn main() {
and then modify the logic of the main function so that if it issues
the usage message it then says return ExitCode::from(BAD_ARGS);
or otherwise at the end of the function it says
ExitCode::SUCCESS (note that at the end of a function the
return keyword is optional since the last expression not
followed by a semicolon is considered to be the function's result).
Compile and run your program with no command line arguments, and record the
output that was produced. Then immediately issue the command
echo $? and record the output it produced (which was the value
that the program returned). Run your program again with at least one
command line argument and record the output that was produced. Then again
immediately issue the command echo $? and record the output it
produced. As the answer to this exercise please show all of those outputs.
Modify your main function's signature
so that it returns a Result type, as in
fn main() -> Result<(), u8> {
instead of fn main() -> ExitCode {
and then modify the logic of the main function so that instead of saying
return ExitCode::from(BAD_ARGS); it says
return Err(BAD_ARGS) and instead of saying
ExitCode::SUCCESS it says Ok(()).
Compile and run your program with no command line arguments, and record the
output that was produced. Then immediately issue the command
echo $? and record the output it produced (which was the value
that the program returned). Run your program again with at least one
command line argument and record the output that was produced. Then again
immediately issue the command echo $? and record the output it
produced. As the answer to this exercise please say briefly whether the
outputs you saw from this exercise differed from the ones from the previous
exercise, and if so how they differed.
Change into the directory you created for this studio, and in it use the cargo new command to
create a new
package (named e.g., rusterrors).
Change into the src directory within that package and edit the
main.rs file that it contains.
Modify the main function so that it prints out the value
of an arithmetic expression that uses arithmetic operators on numeric
variables initialized to appropriate values to produce a non-trivial
expression that causes a division by zero (i.e., don't just divide by 0, but
rather divide by a sub-expression that evaluates to 0).
Compile and run your program and as the answer to this exercise please (1) show code you wrote and the output that was produced by the program, and (2) explain briefly how Rust handled the division by zero.
Set the RUST_BACKTRACE environment variable in your terminal
window by issuing the command export RUST_BACKTRACE=1 and then
checking to make sure that worked by issuing the command echo
$RUST_BACKTRACE to confirm its value.
Run your code from the previous exercise again to show the call stack at
the point where the division by zero occurred, and save a copy of the output
the program produced.
Modify the initialization values of the variables in the main function so that the expression does not divide by zero. Compile and run your code, and as the answer to this exercise please show the output produced from the run where the program did not divide by zero, and from the run where it did.
Again change into the top-level directory you created for this studio, and use the
cargo new command to create a new
package (named e.g., rustmodules).
Change into the src directory within that package and edit the
main.rs file that it contains.
Outside of the main function, declare a pub const item of type
usize that is initialized to an unsigned integer value of your
choosing. Then, modify the main function so that it prints out
the value of that constant. Compile and run your program and as the answer
to this exercise please show the code you wrote and the output of the program.
Make a copy of the declaration you added in the previous exercise and decorate the original declaration with a conditional compilation attribute, e.g.,
#[cfg(oldexercise)] pub const ... , to preserve it.
Put the copy of the declaration outside of the main function, and in it change
pub const to pub static. Compile and run your
program and as the answer to this exercise please show the code you wrote and
the output of the program.
Make a copy of the declaration you added in the previous exercise and decorate the original declaration with a conditional compilation attribute, e.g.,
#[cfg(oldexercise)] pub static ... , to preserve it.
Put the copy of the declaration outside of the main function, and in it change
pub static to pub static mut. In your main function
then assign a new value to the public static variable. Compile and run your
program and as the answer to this exercise please show the error that was
produced.
Inside of your main function, put an unsafe { ... } block around
the code it contains. Compile and run your program and as the answer to this
exercise please show the code you wrote and the output of the program.
Make a copy of the declaration you added in the exercise before the previous exercise and decorate the original declaration with a conditional compilation attribute, e.g.,
#[cfg(oldexercise)] pub static mut ... , to preserve it.
Outside of the main function, add the line:
use std::sync::atomic::{AtomicUsize, Ordering};
and immediately below it declare a static variable of type
AtomicUsize that is initialized to an unsigned integer value of
your choosing.
Put a conditional compilation block around the contents of your main function to preserve them, e.g.,
#[cfg(oldexercise)] {unsafe {...}}
and then in the main function outside of that block (1) call the
load method with Ordering::SeqCst on the
AtomicUsize and print out the value that call returns,
(2) call the store method with a different unsigned integer and
Ordering::SeqCst on the AtomicUsize to change
its value, and then (3) again call the load method with
Ordering::SeqCst on the AtomicUsize and print out
the value that call returns. Compile and run your program and as the answer
to this exercise please show the code you wrote and the output of the program.
In your main.rs file, declare a module block that surrounds all
the code that file contains. Compile your program, and as the answer to this
exercise please show the error(s) that occurred.
Move only the main function out of the module block (put it below the code encapsulated by the module block), compile your program, and as the answer to this exercise please show the error(s) that occurred.
Modify the use statement within the module so that it only
brings in std::sync::atomic::AtomicUsize; (and does not bring
in std::sync::atomic::Ordering;) and also change the
declaration of the AtomicUsize variable to make it public.
Then, inside of the main function, add use statements for
the AtomicUsize variable within the module and also for
std::sync::atomic::Ordering;. Compile and run your program and
as the answer to this exercise please show the code you wrote and the output
of the program.
Once a program has been compiled, you can run the binary that
was produced directly. Try that out by issuing the command
./target/debug/hello
from within the hello directory under the top-level directory
for this studio, and as
the answer to this exercise please show the output that was produced.
In this exercise and the next one you will attempt to access elements
outside of the range of the vector in the cmdargs code.
The program name is kept in position 0 of the vector, and accessing that
position is safe. However,
attempting to use a negative value (e.g., -1) to index into the vector should
produce a compile time error. Try that within your cmdargs
program, and as the answer to this exercise
please show the error message that was issued.
Indexing with positive values that are too large will also be caught by Rust, but that may not occur until run-time. Instead of using a negative value as in the previous exercise, try using the length of the vector (which because vector indexing is 0-based in Rust will be one past the last valid element) and as the answer to this exercise please show the error message that was issued.
Modify the main function in the rusterrors package so that it
calculates
the numerator and the denominator of the expression as separate variables, and
then checks whether or not the denominator is zero. Modify the main
function's logic so that if the denominator is zero it returns an error code
and otherwise it calculates the expression and returns the result.
Compile and run your program twice, once with initialization values that case the function to divide by zero and once with ones that don't. As the answer to this exercise please show the output the program produced in each of the runs, and also a copy of the code for one of them.
For this studio, please turn in the following:
hello, cmdargs,
rusterrors, and rustmodules
packages, after all the modifications made to them in the exercises
above.