SC HW 1 Griffin Loiselle - TheEvergreenStateCollege/upper-division-cs-23-24 GitHub Wiki
SC HW 1
Griffin Loiselle
Rustlings:
How do I compile rust code? rustc name.rs -compiles the file
./name -executes file
Example:
Variables:
Variables 5 has two interesting errors:
Here is the code:
For the first error there is a type mismatch. The variable number is assigned an integer value, and then is reassigned the value of an integer. This brings up another error; the variable number is not mutable, so it should not be able to have its value reassigned.
First I'll make the variable mutable. Then I'll cast the number three to be a string. To do this I can add quotes around the 3 to make it a string, or I could call the .to_string() method on 3. Note: adding parentheses doesn't technically cast it to integer, instead it assigns the value as a string initially.
Now for the second error:
A string and an integer are being added together, so we receive type mismatch error.
I believe if I cast the int to a String that the values will be appended, so that won't work. Instead I'll need to cast the variable number to an integer. I'm wondering if this will work. I don't know how casting works with owner ship.
I used the hint command and it seems my approach is off. They want me to use shadowing: https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing
Shadowing is when you create a variable with the same name as another variable. The compiler refers to the second variable from that point forth.
So I'm going to reapproach the problem using shadowing.
In Variables6 I learned two things:
- constants can be declared in any scope, including globally
- the type must be stated
Functions
In Rust you can specify a return type using -> Also Rust automatically returns the last expression in a function if not specified. Note: take off the semi colon of the last expression
If
Primitive Types
How do I create an array?
This solution would take a lot of time to make if there are 100 elements, so how can I create an array with 100 elements?
This solution ^^ also has the same problem as above.
So here is a solution where I can populate each element in the array with the same value. This way I don't have to manually assign each element a value.
How would I loop through an array and assign each element a value? Would the array need to be mutable?
The Slice Type: -A way to reference a contiguous sequence of elements in a collection -a type of reference, so it does not have ownership