53 lines
1.6 KiB
Markdown
53 lines
1.6 KiB
Markdown
# What we did:
|
|
Created a guessing game! This file takes in a number from the user, generates
|
|
a random number, and compares the two to say whether the guess is correct,
|
|
lower, or higher. It introduces us to key concepts in Rust such as module
|
|
importing, the idea of mutability, how to define variables, and other
|
|
interesting type things.
|
|
|
|
## Breaking Down some things
|
|
### Types, and variants
|
|
When creating the variable `guess` we created it as
|
|
|
|
```rust
|
|
let mut guess = String::new();
|
|
```
|
|
|
|
where we call `String::new()`. `String` is a type, that has a function `new`
|
|
integrated into that type.
|
|
|
|
Then, we read in the data. Some interesting things happen here:
|
|
1. We use `&mut guess` where `&` signifies a *reference* to an object
|
|
2. We have an `.expect()`
|
|
a. `.read_line` returns a string, but it also returns a result
|
|
b. This result is an *enumeration* type, with each possible
|
|
result being a *variant*.
|
|
|
|
Wacky stuff.
|
|
|
|
Next, we do some interesting things with strings. Printing strings uses
|
|
curly brackets, kind of like python. These can hold the variable, or
|
|
use an expression that is later in the print statement. Like this:
|
|
|
|
```rust
|
|
let x = 6;
|
|
let guess = 3;
|
|
println!("You guessed: {}, {x}", guess);
|
|
|
|
>> You guessed 3, 6
|
|
```
|
|
|
|
### Casting Types and Switching between ints and floats
|
|
Rust is particular about integers and floats. if something is u32, it will
|
|
not infer switching to f32 when doing an operation between the two. Instead,
|
|
an error is created. To deal with this, you have to use the 'as' command
|
|
|
|
```rust
|
|
let a: u32 = 1
|
|
let b: u32 = 2
|
|
let mut c: f32 = (a + b as f32)
|
|
```
|
|
|
|
The above code will work just fine.
|
|
|