Merge branch 'main' into main

This commit is contained in:
tajo48 2023-06-15 00:46:45 +02:00 committed by GitHub
commit e1704a2f1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
99 changed files with 748 additions and 425 deletions

View File

@ -2136,6 +2136,69 @@
"contributions": [ "contributions": [
"content" "content"
] ]
},
{
"login": "proofconstruction",
"name": "proofconstruction",
"avatar_url": "https://avatars.githubusercontent.com/u/74747193?v=4",
"profile": "https://github.com/proofconstruction",
"contributions": [
"infra"
]
},
{
"login": "IVIURRAY",
"name": "IVIURRAY",
"avatar_url": "https://avatars.githubusercontent.com/u/16007179?v=4",
"profile": "https://www.youtube.com/channel/UCQCjA6qUutAtWqkCA4Z36CQ",
"contributions": [
"content"
]
},
{
"login": "b-apperlo",
"name": "Bert Apperlo",
"avatar_url": "https://avatars.githubusercontent.com/u/91734527?v=4",
"profile": "https://github.com/b-apperlo",
"contributions": [
"content"
]
},
{
"login": "FWDekker",
"name": "Florine W. Dekker",
"avatar_url": "https://avatars.githubusercontent.com/u/13442533?v=4",
"profile": "https://fwdekker.com/",
"contributions": [
"content"
]
},
{
"login": "luhem7",
"name": "Mehul Gangavelli",
"avatar_url": "https://avatars.githubusercontent.com/u/4008215?v=4",
"profile": "https://github.com/luhem7",
"contributions": [
"content"
]
},
{
"login": "Frosthage",
"name": "Mikael Frosthage",
"avatar_url": "https://avatars.githubusercontent.com/u/14823314?v=4",
"profile": "https://github.com/Frosthage",
"contributions": [
"content"
]
},
{
"login": "robertefry",
"name": "Robert Fry",
"avatar_url": "https://avatars.githubusercontent.com/u/43712054?v=4",
"profile": "https://robertfry.xyz",
"contributions": [
"content"
]
} }
], ],
"contributorsPerLine": 8, "contributorsPerLine": 8,
@ -2144,5 +2207,6 @@
"repoType": "github", "repoType": "github",
"repoHost": "https://github.com", "repoHost": "https://github.com",
"skipCi": true, "skipCi": true,
"commitConvention": "angular" "commitConvention": "angular",
"commitType": "docs"
} }

View File

@ -14,6 +14,8 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Fetch & maybe update Cargo.lock
run: cargo fetch --locked
- name: Build - name: Build
run: cargo build --verbose run: cargo build --verbose
- name: Run tests - name: Run tests

View File

@ -303,6 +303,15 @@ authors.
<tr> <tr>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/b1ue64"><img src="https://avatars.githubusercontent.com/u/77976308?v=4?s=100" width="100px;" alt="b1ue64"/><br /><sub><b>b1ue64</b></sub></a><br /><a href="#content-b1ue64" title="Content">🖋</a></td> <td align="center" valign="top" width="12.5%"><a href="https://github.com/b1ue64"><img src="https://avatars.githubusercontent.com/u/77976308?v=4?s=100" width="100px;" alt="b1ue64"/><br /><sub><b>b1ue64</b></sub></a><br /><a href="#content-b1ue64" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/lazywalker"><img src="https://avatars.githubusercontent.com/u/53956?v=4?s=100" width="100px;" alt="lazywalker"/><br /><sub><b>lazywalker</b></sub></a><br /><a href="#content-lazywalker" title="Content">🖋</a></td> <td align="center" valign="top" width="12.5%"><a href="https://github.com/lazywalker"><img src="https://avatars.githubusercontent.com/u/53956?v=4?s=100" width="100px;" alt="lazywalker"/><br /><sub><b>lazywalker</b></sub></a><br /><a href="#content-lazywalker" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/proofconstruction"><img src="https://avatars.githubusercontent.com/u/74747193?v=4?s=100" width="100px;" alt="proofconstruction"/><br /><sub><b>proofconstruction</b></sub></a><br /><a href="#infra-proofconstruction" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://www.youtube.com/channel/UCQCjA6qUutAtWqkCA4Z36CQ"><img src="https://avatars.githubusercontent.com/u/16007179?v=4?s=100" width="100px;" alt="IVIURRAY"/><br /><sub><b>IVIURRAY</b></sub></a><br /><a href="#content-IVIURRAY" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/b-apperlo"><img src="https://avatars.githubusercontent.com/u/91734527?v=4?s=100" width="100px;" alt="Bert Apperlo"/><br /><sub><b>Bert Apperlo</b></sub></a><br /><a href="#content-b-apperlo" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://fwdekker.com/"><img src="https://avatars.githubusercontent.com/u/13442533?v=4?s=100" width="100px;" alt="Florine W. Dekker"/><br /><sub><b>Florine W. Dekker</b></sub></a><br /><a href="#content-FWDekker" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/luhem7"><img src="https://avatars.githubusercontent.com/u/4008215?v=4?s=100" width="100px;" alt="Mehul Gangavelli"/><br /><sub><b>Mehul Gangavelli</b></sub></a><br /><a href="#content-luhem7" title="Content">🖋</a></td>
<td align="center" valign="top" width="12.5%"><a href="https://github.com/Frosthage"><img src="https://avatars.githubusercontent.com/u/14823314?v=4?s=100" width="100px;" alt="Mikael Frosthage"/><br /><sub><b>Mikael Frosthage</b></sub></a><br /><a href="#content-Frosthage" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center" valign="top" width="12.5%"><a href="https://robertfry.xyz"><img src="https://avatars.githubusercontent.com/u/43712054?v=4?s=100" width="100px;" alt="Robert Fry"/><br /><sub><b>Robert Fry</b></sub></a><br /><a href="#content-robertefry" title="Content">🖋</a></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@ -1,10 +1,13 @@
// clippy1.rs // clippy1.rs
// The Clippy tool is a collection of lints to analyze your code
// so you can catch common mistakes and improve your Rust code.
// //
// For these exercises the code will fail to compile when there are clippy warnings // The Clippy tool is a collection of lints to analyze your code so you can
// check clippy's suggestions from the output to solve the exercise. // catch common mistakes and improve your Rust code.
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a hint. //
// For these exercises the code will fail to compile when there are clippy
// warnings check clippy's suggestions from the output to solve the exercise.
//
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// clippy2.rs // clippy2.rs
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,8 @@
// clippy3.rs // clippy3.rs
//
// Here's a couple more easy Clippy fixes, so you can see its utility. // Here's a couple more easy Clippy fixes, so you can see its utility.
//
// Execute `rustlings hint clippy3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,11 @@
// AsRef and AsMut allow for cheap reference-to-reference conversions. // as_ref_mut.rs
// Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html //
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // AsRef and AsMut allow for cheap reference-to-reference conversions. Read more
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint. // about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and
// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
//
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,11 @@
// The From trait is used for value-to-value conversions. // from_into.rs
// If From is implemented correctly for a type, the Into trait should work conversely. //
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html // The From trait is used for value-to-value conversions. If From is implemented
// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a hint. // correctly for a type, the Into trait should work conversely. You can read
// more about it at https://doc.rust-lang.org/std/convert/trait.From.html
//
// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a
// hint.
#[derive(Debug)] #[derive(Debug)]
struct Person { struct Person {
@ -20,20 +24,21 @@ impl Default for Person {
} }
} }
// Your task is to complete this implementation // Your task is to complete this implementation in order for the line `let p =
// in order for the line `let p = Person::from("Mark,20")` to compile // Person::from("Mark,20")` to compile Please note that you'll need to parse the
// Please note that you'll need to parse the age component into a `usize` // age component into a `usize` with something like `"4".parse::<usize>()`. The
// with something like `"4".parse::<usize>()`. The outcome of this needs to // outcome of this needs to be handled appropriately.
// be handled appropriately.
// //
// Steps: // Steps:
// 1. If the length of the provided string is 0, then return the default of Person // 1. If the length of the provided string is 0, then return the default of
// 2. Split the given string on the commas present in it // Person.
// 3. Extract the first element from the split operation and use it as the name // 2. Split the given string on the commas present in it.
// 4. If the name is empty, then return the default of Person // 3. Extract the first element from the split operation and use it as the name.
// 5. Extract the other element from the split operation and parse it into a `usize` as the age // 4. If the name is empty, then return the default of Person.
// If while parsing the age, something goes wrong, then return the default of Person // 5. Extract the other element from the split operation and parse it into a
// Otherwise, then return an instantiated Person object with the results // `usize` as the age.
// If while parsing the age, something goes wrong, then return the default of
// Person Otherwise, then return an instantiated Person object with the results
// I AM NOT DONE // I AM NOT DONE
@ -77,7 +82,8 @@ mod tests {
} }
#[test] #[test]
fn test_bad_age() { fn test_bad_age() {
// Test that "Mark,twenty" will return the default person due to an error in parsing age // Test that "Mark,twenty" will return the default person due to an
// error in parsing age
let p = Person::from("Mark,twenty"); let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John"); assert_eq!(p.name, "John");
assert_eq!(p.age, 30); assert_eq!(p.age, 30);

View File

@ -1,10 +1,13 @@
// from_str.rs // from_str.rs
// This is similar to from_into.rs, but this time we'll implement `FromStr` //
// and return errors instead of falling back to a default value. // This is similar to from_into.rs, but this time we'll implement `FromStr` and
// Additionally, upon implementing FromStr, you can use the `parse` method // return errors instead of falling back to a default value. Additionally, upon
// on strings to generate an object of the implementor type. // implementing FromStr, you can use the `parse` method on strings to generate
// You can read more about it at https://doc.rust-lang.org/std/str/trait.FromStr.html // an object of the implementor type. You can read more about it at
// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a hint. // https://doc.rust-lang.org/std/str/trait.FromStr.html
//
// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a
// hint.
use std::num::ParseIntError; use std::num::ParseIntError;
use std::str::FromStr; use std::str::FromStr;
@ -33,15 +36,18 @@ enum ParsePersonError {
// Steps: // Steps:
// 1. If the length of the provided string is 0, an error should be returned // 1. If the length of the provided string is 0, an error should be returned
// 2. Split the given string on the commas present in it // 2. Split the given string on the commas present in it
// 3. Only 2 elements should be returned from the split, otherwise return an error // 3. Only 2 elements should be returned from the split, otherwise return an
// error
// 4. Extract the first element from the split operation and use it as the name // 4. Extract the first element from the split operation and use it as the name
// 5. Extract the other element from the split operation and parse it into a `usize` as the age // 5. Extract the other element from the split operation and parse it into a
// with something like `"4".parse::<usize>()` // `usize` as the age with something like `"4".parse::<usize>()`
// 6. If while extracting the name and the age something goes wrong, an error should be returned // 6. If while extracting the name and the age something goes wrong, an error
// should be returned
// If everything goes well, then return a Result of a Person object // If everything goes well, then return a Result of a Person object
// //
// As an aside: `Box<dyn Error>` implements `From<&'_ str>`. This means that if you want to return a // As an aside: `Box<dyn Error>` implements `From<&'_ str>`. This means that if
// string error message, you can do so via just using return `Err("my error message".into())`. // you want to return a string error message, you can do so via just using
// return `Err("my error message".into())`.
impl FromStr for Person { impl FromStr for Person {
type Err = ParsePersonError; type Err = ParsePersonError;

View File

@ -1,9 +1,13 @@
// try_from_into.rs // try_from_into.rs
// TryFrom is a simple and safe type conversion that may fail in a controlled way under some circumstances. //
// Basically, this is the same as From. The main difference is that this should return a Result type // TryFrom is a simple and safe type conversion that may fail in a controlled
// instead of the target type itself. // way under some circumstances. Basically, this is the same as From. The main
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.TryFrom.html // difference is that this should return a Result type instead of the target
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for a hint. // type itself. You can read more about it at
// https://doc.rust-lang.org/std/convert/trait.TryFrom.html
//
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for
// a hint.
use std::convert::{TryFrom, TryInto}; use std::convert::{TryFrom, TryInto};
@ -25,14 +29,13 @@ enum IntoColorError {
// I AM NOT DONE // I AM NOT DONE
// Your task is to complete this implementation // Your task is to complete this implementation and return an Ok result of inner
// and return an Ok result of inner type Color. // type Color. You need to create an implementation for a tuple of three
// You need to create an implementation for a tuple of three integers, // integers, an array of three integers, and a slice of integers.
// an array of three integers, and a slice of integers.
// //
// Note that the implementation for tuple and array will be checked at compile time, // Note that the implementation for tuple and array will be checked at compile
// but the slice implementation needs to check the slice length! // time, but the slice implementation needs to check the slice length! Also note
// Also note that correct RGB color values must be integers in the 0..=255 range. // that correct RGB color values must be integers in the 0..=255 range.
// Tuple implementation // Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<(i16, i16, i16)> for Color {

View File

@ -1,10 +1,14 @@
// Type casting in Rust is done via the usage of the `as` operator. // using_as.rs
// Please note that the `as` operator is not only used when type casting.
// It also helps with renaming imports.
// //
// The goal is to make sure that the division does not fail to compile // Type casting in Rust is done via the usage of the `as` operator. Please note
// and returns the proper type. // that the `as` operator is not only used when type casting. It also helps with
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint. // renaming imports.
//
// The goal is to make sure that the division does not fail to compile and
// returns the proper type.
//
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,4 +1,5 @@
// enums1.rs // enums1.rs
//
// No hints this time! ;) // No hints this time! ;)
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// enums2.rs // enums2.rs
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// enums3.rs // enums3.rs
//
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -17,6 +20,7 @@ struct State {
color: (u8, u8, u8), color: (u8, u8, u8),
position: Point, position: Point,
quit: bool, quit: bool,
message: String
} }
impl State { impl State {
@ -28,17 +32,17 @@ impl State {
self.quit = true; self.quit = true;
} }
fn echo(&self, s: String) { fn echo(&mut self, s: String) { self.message = s }
println!("{}", s);
}
fn move_position(&mut self, p: Point) { fn move_position(&mut self, p: Point) {
self.position = p; self.position = p;
} }
fn process(&mut self, message: Message) { fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants // TODO: create a match expression to process the different message
// Remember: When passing a tuple as a function argument, you'll need extra parentheses: fn function((t, u, p, l, e)) // variants
// Remember: When passing a tuple as a function argument, you'll need
// extra parentheses: fn function((t, u, p, l, e))
} }
} }
@ -52,6 +56,7 @@ mod tests {
quit: false, quit: false,
position: Point { x: 0, y: 0 }, position: Point { x: 0, y: 0 },
color: (0, 0, 0), color: (0, 0, 0),
message: "hello world".to_string(),
}; };
state.process(Message::ChangeColor(255, 0, 255)); state.process(Message::ChangeColor(255, 0, 255));
state.process(Message::Echo(String::from("hello world"))); state.process(Message::Echo(String::from("hello world")));
@ -62,5 +67,6 @@ mod tests {
assert_eq!(state.position.x, 10); assert_eq!(state.position.x, 10);
assert_eq!(state.position.y, 15); assert_eq!(state.position.y, 15);
assert_eq!(state.quit, true); assert_eq!(state.quit, true);
assert_eq!(state.message, "hello world");
} }
} }

View File

@ -1,9 +1,13 @@
// errors1.rs // errors1.rs
// This function refuses to generate text to be printed on a nametag if //
// you pass it an empty string. It'd be nicer if it explained what the problem // This function refuses to generate text to be printed on a nametag if you pass
// was, instead of just sometimes returning `None`. Thankfully, Rust has a similar // it an empty string. It'd be nicer if it explained what the problem was,
// construct to `Option` that can be used to express error conditions. Let's use it! // instead of just sometimes returning `None`. Thankfully, Rust has a similar
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint. // construct to `Option` that can be used to express error conditions. Let's use
// it!
//
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,21 +1,23 @@
// errors2.rs // errors2.rs
//
// Say we're writing a game where you can buy items with tokens. All items cost // Say we're writing a game where you can buy items with tokens. All items cost
// 5 tokens, and whenever you purchase items there is a processing fee of 1 // 5 tokens, and whenever you purchase items there is a processing fee of 1
// token. A player of the game will type in how many items they want to buy, // token. A player of the game will type in how many items they want to buy, and
// and the `total_cost` function will calculate the total cost of the tokens. // the `total_cost` function will calculate the total cost of the tokens. Since
// Since the player typed in the quantity, though, we get it as a string-- and // the player typed in the quantity, though, we get it as a string-- and they
// they might have typed anything, not just numbers! // might have typed anything, not just numbers!
//
// Right now, this function isn't handling the error case at all (and isn't // Right now, this function isn't handling the error case at all (and isn't
// handling the success case properly either). What we want to do is: // handling the success case properly either). What we want to do is: if we call
// if we call the `parse` function on a string that is not a number, that // the `parse` function on a string that is not a number, that function will
// function will return a `ParseIntError`, and in that case, we want to // return a `ParseIntError`, and in that case, we want to immediately return
// immediately return that error from our function and not try to multiply // that error from our function and not try to multiply and add.
// and add. //
// There are at least two ways to implement this that are both correct-- but one
// There are at least two ways to implement this that are both correct-- but // is a lot shorter!
// one is a lot shorter! //
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// errors3.rs // errors3.rs
//
// This is a program that is trying to use a completed version of the // This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though! // `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it? // Why not? What should we do to fix it?
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// errors4.rs // errors4.rs
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,20 +1,26 @@
// errors5.rs // errors5.rs
//
// This program uses an altered version of the code from errors4. // This program uses an altered version of the code from errors4.
//
// This exercise uses some concepts that we won't get to until later in the course, like `Box` and the // This exercise uses some concepts that we won't get to until later in the
// `From` trait. It's not important to understand them in detail right now, but you can read ahead if you like. // course, like `Box` and the `From` trait. It's not important to understand
// For now, think of the `Box<dyn ???>` type as an "I want anything that does ???" type, which, given // them in detail right now, but you can read ahead if you like. For now, think
// Rust's usual standards for runtime safety, should strike you as somewhat lenient! // of the `Box<dyn ???>` type as an "I want anything that does ???" type, which,
// given Rust's usual standards for runtime safety, should strike you as
// In short, this particular use case for boxes is for when you want to own a value and you care only that it is a // somewhat lenient!
// type which implements a particular trait. To do so, The Box is declared as of type Box<dyn Trait> where Trait is the trait //
// the compiler looks for on any value used in that context. For this exercise, that context is the potential errors // In short, this particular use case for boxes is for when you want to own a
// which can be returned in a Result. // value and you care only that it is a type which implements a particular
// trait. To do so, The Box is declared as of type Box<dyn Trait> where Trait is
// What can we use to describe both errors? In other words, is there a trait which both errors implement? // the trait the compiler looks for on any value used in that context. For this
// exercise, that context is the potential errors which can be returned in a
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a hint. // Result.
//
// What can we use to describe both errors? In other words, is there a trait
// which both errors implement?
//
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,12 +1,13 @@
// errors6.rs // errors6.rs
//
// Using catch-all error types like `Box<dyn error::Error>` isn't recommended // Using catch-all error types like `Box<dyn error::Error>` isn't recommended
// for library code, where callers might want to make decisions based on the // for library code, where callers might want to make decisions based on the
// error content, instead of printing it out or propagating it further. Here, // error content, instead of printing it out or propagating it further. Here, we
// we define a custom error type to make it possible for callers to decide // define a custom error type to make it possible for callers to decide what to
// what to do next when our function returns an error. // do next when our function returns an error.
//
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// functions1.rs // functions1.rs
// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// functions2.rs // functions2.rs
// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// functions3.rs // functions3.rs
// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,11 +1,12 @@
// functions4.rs // functions4.rs
// Execute `rustlings hint functions4` or use the `hint` watch subcommand for a hint. //
// This store is having a sale where if the price is an even number, you get 10
// This store is having a sale where if the price is an even number, you get // Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. (Don't worry
// 10 Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. // about the function bodies themselves, we're only interested in the signatures
// (Don't worry about the function bodies themselves, we're only interested // for now. If anything, this is a good way to peek ahead to future exercises!)
// in the signatures for now. If anything, this is a good way to peek ahead //
// to future exercises!) // Execute `rustlings hint functions4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// functions5.rs // functions5.rs
// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// This shopping list program isn't compiling! // generics1.rs
// Use your knowledge of generics to fix it. //
// This shopping list program isn't compiling! Use your knowledge of generics to
// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. // fix it.
//
// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// generics2.rs
//
// This powerful wrapper provides the ability to store a positive integer value. // This powerful wrapper provides the ability to store a positive integer value.
// Rewrite it using generics so that it supports wrapping ANY type. // Rewrite it using generics so that it supports wrapping ANY type.
//
// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,14 +1,15 @@
// hashmaps1.rs // hashmaps1.rs
// A basket of fruits in the form of a hash map needs to be defined. //
// The key represents the name of the fruit and the value represents // A basket of fruits in the form of a hash map needs to be defined. The key
// how many of that particular fruit is in the basket. You have to put // represents the name of the fruit and the value represents how many of that
// at least three different types of fruits (e.g apple, banana, mango) // particular fruit is in the basket. You have to put at least three different
// in the basket and the total count of all the fruits should be at // types of fruits (e.g apple, banana, mango) in the basket and the total count
// least five. // of all the fruits should be at least five.
// //
// Make me compile and pass the tests! // Make me compile and pass the tests!
// //
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,17 +1,18 @@
// hashmaps2.rs // hashmaps2.rs
// We're collecting different fruits to bake a delicious fruit cake. //
// For this, we have a basket, which we'll represent in the form of a hash // We're collecting different fruits to bake a delicious fruit cake. For this,
// map. The key represents the name of each fruit we collect and the value // we have a basket, which we'll represent in the form of a hash map. The key
// represents how many of that particular fruit we have collected. // represents the name of each fruit we collect and the value represents how
// Three types of fruits - Apple (4), Mango (2) and Lychee (5) are already // many of that particular fruit we have collected. Three types of fruits -
// in the basket hash map. // Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
// You must add fruit to the basket so that there is at least // must add fruit to the basket so that there is at least one of each kind and
// one of each kind and more than 11 in total - we have a lot of mouths to feed. // more than 11 in total - we have a lot of mouths to feed. You are not allowed
// You are not allowed to insert any more of these fruits! // to insert any more of these fruits!
// //
// Make me pass the tests! // Make me pass the tests!
// //
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -36,9 +37,9 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
]; ];
for fruit in fruit_kinds { for fruit in fruit_kinds {
// TODO: Insert new fruits if they are not already present in the basket. // TODO: Insert new fruits if they are not already present in the
// Note that you are not allowed to put any type of fruit that's already // basket. Note that you are not allowed to put any type of fruit that's
// present! // already present!
} }
} }
@ -80,4 +81,13 @@ mod tests {
let count = basket.values().sum::<u32>(); let count = basket.values().sum::<u32>();
assert!(count > 11); assert!(count > 11);
} }
#[test]
fn all_fruit_types_in_basket() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
for amount in basket.values() {
assert_ne!(amount, &0);
}
}
} }

View File

@ -1,26 +1,25 @@
// hashmaps3.rs // hashmaps3.rs
//
// A list of scores (one per line) of a soccer match is given. Each line // A list of scores (one per line) of a soccer match is given. Each line is of
// is of the form : // the form : "<team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>"
// <team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>
// Example: England,France,4,2 (England scored 4 goals, France 2). // Example: England,France,4,2 (England scored 4 goals, France 2).
//
// You have to build a scores table containing the name of the team, goals // You have to build a scores table containing the name of the team, goals the
// the team scored, and goals the team conceded. One approach to build // team scored, and goals the team conceded. One approach to build the scores
// the scores table is to use a Hashmap. The solution is partially // table is to use a Hashmap. The solution is partially written to use a
// written to use a Hashmap, complete it to pass the test. // Hashmap, complete it to pass the test.
//
// Make me pass the tests! // Make me pass the tests!
//
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
use std::collections::HashMap; use std::collections::HashMap;
// A structure to store team name and its goal details. // A structure to store the goal details of a team.
struct Team { struct Team {
name: String,
goals_scored: u8, goals_scored: u8,
goals_conceded: u8, goals_conceded: u8,
} }

View File

@ -1,4 +1,5 @@
// if1.rs // if1.rs
//
// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,8 @@
// if2.rs // if2.rs
//
// Step 1: Make me compile! // Step 1: Make me compile!
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing! // Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
//
// Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,13 +1,17 @@
// intro1.rs // intro1.rs
//
// About this `I AM NOT DONE` thing: // About this `I AM NOT DONE` thing:
// We sometimes encourage you to keep trying things on a given exercise, even // We sometimes encourage you to keep trying things on a given exercise, even
// after you already figured it out. If you got everything working and feel // after you already figured it out. If you got everything working and feel
// ready for the next exercise, remove the `I AM NOT DONE` comment below. // ready for the next exercise, remove the `I AM NOT DONE` comment below.
// Execute `rustlings hint intro1` or use the `hint` watch subcommand for a hint.
// //
// If you're running this using `rustlings watch`: The exercise file will be reloaded // If you're running this using `rustlings watch`: The exercise file will be
// when you change one of the lines below! Try adding a `println!` line, or try changing // reloaded when you change one of the lines below! Try adding a `println!`
// what it outputs in your terminal. Try removing a semicolon and see what happens! // line, or try changing what it outputs in your terminal. Try removing a
// semicolon and see what happens!
//
// Execute `rustlings hint intro1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// intro2.rs // intro2.rs
//
// Make the code print a greeting to the world. // Make the code print a greeting to the world.
// Execute `rustlings hint intro2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint intro2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,12 +1,13 @@
// iterators1.rs // iterators1.rs
// //
// Make me compile by filling in the `???`s // When performing operations on elements within a collection, iterators are
// essential. This module helps you get familiar with the structure of using an
// iterator and how to go through elements within an iterable collection.
// //
// When performing operations on elements within a collection, iterators are essential. // Make me compile by filling in the `???`s
// This module helps you get familiar with the structure of using an iterator and
// how to go through elements within an iterable collection.
// //
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// iterators2.rs // iterators2.rs
//
// In this exercise, you'll learn some of the unique advantages that iterators // In this exercise, you'll learn some of the unique advantages that iterators
// can offer. Follow the steps to complete the exercise. // can offer. Follow the steps to complete the exercise.
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,10 +1,13 @@
// iterators3.rs // iterators3.rs
// This is a bigger exercise than most of the others! You can do it! //
// Here is your mission, should you choose to accept it: // This is a bigger exercise than most of the others! You can do it! Here is
// your mission, should you choose to accept it:
// 1. Complete the divide function to get the first four tests to pass. // 1. Complete the divide function to get the first four tests to pass.
// 2. Get the remaining tests to pass by completing the result_with_list and // 2. Get the remaining tests to pass by completing the result_with_list and
// list_of_results functions. // list_of_results functions.
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -26,14 +29,16 @@ pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
todo!(); todo!();
} }
// Complete the function and return a value of the correct type so the test passes. // Complete the function and return a value of the correct type so the test
// passes.
// Desired output: Ok([1, 11, 1426, 3]) // Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> () { fn result_with_list() -> () {
let numbers = vec![27, 297, 38502, 81]; let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27)); let division_results = numbers.into_iter().map(|n| divide(n, 27));
} }
// Complete the function and return a value of the correct type so the test passes. // Complete the function and return a value of the correct type so the test
// passes.
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
fn list_of_results() -> () { fn list_of_results() -> () {
let numbers = vec![27, 297, 38502, 81]; let numbers = vec![27, 297, 38502, 81];

View File

@ -1,5 +1,7 @@
// iterators4.rs // iterators4.rs
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,4 +1,5 @@
// iterators5.rs // iterators5.rs
//
// Let's define a simple model to track Rustlings exercise progress. Progress // Let's define a simple model to track Rustlings exercise progress. Progress
// will be modelled using a hash map. The name of the exercise is the key and // will be modelled using a hash map. The name of the exercise is the key and
// the progress is the value. Two counting functions were created to count the // the progress is the value. Two counting functions were created to count the
@ -6,7 +7,9 @@
// functionality using iterators. Try not to use imperative loops (for, while). // functionality using iterators. Try not to use imperative loops (for, while).
// Only the two iterator methods (count_iterator and count_collection_iterator) // Only the two iterator methods (count_iterator and count_collection_iterator)
// need to be modified. // need to be modified.
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,11 +1,12 @@
// lifetimes1.rs // lifetimes1.rs
// //
// The Rust compiler needs to know how to check whether supplied references are // The Rust compiler needs to know how to check whether supplied references are
// valid, so that it can let the programmer know if a reference is at risk // valid, so that it can let the programmer know if a reference is at risk of
// of going out of scope before it is used. Remember, references are borrows // going out of scope before it is used. Remember, references are borrows and do
// and do not own their own data. What if their owner goes out of scope? // not own their own data. What if their owner goes out of scope?
// //
// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,10 +1,10 @@
// lifetimes2.rs // lifetimes2.rs
// //
// So if the compiler is just validating the references passed // So if the compiler is just validating the references passed to the annotated
// to the annotated parameters and the return type, what do // parameters and the return type, what do we need to change?
// we need to change?
// //
// Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -2,7 +2,8 @@
// //
// Lifetimes are also needed when structs hold references. // Lifetimes are also needed when structs hold references.
// //
// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// macros1.rs // macros1.rs
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// macros2.rs // macros2.rs
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// macros3.rs // macros3.rs
//
// Make me compile, without taking the macro out of the module! // Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// macros4.rs // macros4.rs
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// modules1.rs // modules1.rs
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,11 @@
// modules2.rs // modules2.rs
// You can bring module paths into scopes and provide new names for them with the //
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile. // You can bring module paths into scopes and provide new names for them with
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint. // the 'use' and 'as' keywords. Fix these 'use' statements to make the code
// compile.
//
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,9 +1,12 @@
// modules3.rs // modules3.rs
// You can use the 'use' keyword to bring module paths from modules from anywhere //
// and especially from the Rust standard library into your scope. // You can use the 'use' keyword to bring module paths from modules from
// Bring SystemTime and UNIX_EPOCH // anywhere and especially from the Rust standard library into your scope. Bring
// from the std::time module. Bonus style points if you can do it with one line! // SystemTime and UNIX_EPOCH from the std::time module. Bonus style points if
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint. // you can do it with one line!
//
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// move_semantics1.rs // move_semantics1.rs
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,24 +1,24 @@
// move_semantics2.rs // move_semantics2.rs
// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand for a hint. //
// Expected output: // Expected output:
// vec0 has length 3 content `[22, 44, 66]` // vec0 has length 3, with contents `[22, 44, 66]`
// vec1 has length 4 content `[22, 44, 66, 88]` // vec1 has length 4, with contents `[22, 44, 66, 88]`
//
// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE
fn main() { fn main() {
let vec0 = Vec::new(); let vec0 = Vec::new();
// Do not move the following line!
let mut vec1 = fill_vec(vec0); let mut vec1 = fill_vec(vec0);
// Do not change the following line! println!("{} has length {}, with contents: `{:?}`", "vec0", vec0.len(), vec0);
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
vec1.push(88); vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {}, with contents `{:?}`", "vec1", vec1.len(), vec1);
} }
fn fill_vec(vec: Vec<i32>) -> Vec<i32> { fn fill_vec(vec: Vec<i32>) -> Vec<i32> {

View File

@ -1,7 +1,10 @@
// move_semantics3.rs // move_semantics3.rs
// Make me compile without adding new lines-- just changing existing lines! //
// (no lines with multiple semicolons necessary!) // Make me compile without adding new lines-- just changing existing lines! (no
// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand for a hint. // lines with multiple semicolons necessary!)
//
// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// move_semantics4.rs // move_semantics4.rs
// Refactor this code so that instead of passing `vec0` into the `fill_vec` function, //
// the Vector gets created in the function itself and passed back to the main // Refactor this code so that instead of passing `vec0` into the `fill_vec`
// function. // function, the Vector gets created in the function itself and passed back to
// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand for a hint. // the main function.
//
// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// move_semantics5.rs // move_semantics5.rs
// Make me compile only by reordering the lines in `main()`, but without //
// adding, changing or removing any of them. // Make me compile only by reordering the lines in `main()`, but without adding,
// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand for a hint. // changing or removing any of them.
//
// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// move_semantics6.rs // move_semantics6.rs
// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand for a hint. //
// You can't change anything except adding or removing references. // You can't change anything except adding or removing references.
//
// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// options1.rs // options1.rs
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -7,8 +9,9 @@
// If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them
// all, so there'll be no more left :( // all, so there'll be no more left :(
fn maybe_icecream(time_of_day: u16) -> Option<u16> { fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a value of 0 // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a
// The Option output should gracefully handle cases where time_of_day > 23. // value of 0 The Option output should gracefully handle cases where
// time_of_day > 23.
// TODO: Complete the function body - remember to return an Option! // TODO: Complete the function body - remember to return an Option!
??? ???
} }
@ -28,7 +31,8 @@ mod tests {
#[test] #[test]
fn raw_value() { fn raw_value() {
// TODO: Fix this test. How do you get at the value contained in the Option? // TODO: Fix this test. How do you get at the value contained in the
// Option?
let icecreams = maybe_icecream(12); let icecreams = maybe_icecream(12);
assert_eq!(icecreams, 5); assert_eq!(icecreams, 5);
} }

View File

@ -1,5 +1,7 @@
// options2.rs // options2.rs
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -27,8 +29,9 @@ mod tests {
let mut cursor = range; let mut cursor = range;
// TODO: make this a while let statement - remember that vector.pop also adds another layer of Option<T> // TODO: make this a while let statement - remember that vector.pop also
// You can stack `Option<T>`s into while let and if let // adds another layer of Option<T>. You can stack `Option<T>`s into
// while let and if let.
integer = optional_integers.pop() { integer = optional_integers.pop() {
assert_eq!(integer, cursor); assert_eq!(integer, cursor);
cursor -= 1; cursor -= 1;

View File

@ -1,5 +1,7 @@
// options3.rs // options3.rs
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,10 @@
// primitive_types1.rs // primitive_types1.rs
// Fill in the rest of the line that has code missing! //
// No hints, there's no tricks, just get used to typing these :) // Fill in the rest of the line that has code missing! No hints, there's no
// tricks, just get used to typing these :)
//
// Execute `rustlings hint primitive_types1` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,10 @@
// primitive_types2.rs // primitive_types2.rs
// Fill in the rest of the line that has code missing! //
// No hints, there's no tricks, just get used to typing these :) // Fill in the rest of the line that has code missing! No hints, there's no
// tricks, just get used to typing these :)
//
// Execute `rustlings hint primitive_types2` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// primitive_types3.rs // primitive_types3.rs
//
// Create an array with at least 100 elements in it where the ??? is. // Create an array with at least 100 elements in it where the ??? is.
// Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// primitive_types4.rs // primitive_types4.rs
//
// Get a slice out of Array a where the ??? is so that the test passes. // Get a slice out of Array a where the ??? is so that the test passes.
// Execute `rustlings hint primitive_types4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint primitive_types4` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// primitive_types5.rs // primitive_types5.rs
//
// Destructure the `cat` tuple so that the println will work. // Destructure the `cat` tuple so that the println will work.
// Execute `rustlings hint primitive_types5` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint primitive_types5` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// primitive_types6.rs // primitive_types6.rs
// Use a tuple index to access the second element of `numbers`. //
// You can put the expression for the second element where ??? is so that the test passes. // Use a tuple index to access the second element of `numbers`. You can put the
// Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand for a hint. // expression for the second element where ??? is so that the test passes.
//
// Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,14 +1,17 @@
// quiz1.rs // quiz1.rs
//
// This is a quiz for the following sections: // This is a quiz for the following sections:
// - Variables // - Variables
// - Functions // - Functions
// - If // - If
//
// Mary is buying apples. The price of an apple is calculated as follows: // Mary is buying apples. The price of an apple is calculated as follows:
// - An apple costs 2 rustbucks. // - An apple costs 2 rustbucks.
// - If Mary buys more than 40 apples, each apple only costs 1 rustbuck! // - If Mary buys more than 40 apples, each apple only costs 1 rustbuck!
// Write a function that calculates the price of an order of apples given // Write a function that calculates the price of an order of apples given the
// the quantity bought. No hints this time! // quantity bought. No hints this time!
//
// No hints this time ;)
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,14 +1,15 @@
// quiz2.rs // quiz2.rs
//
// This is a quiz for the following sections: // This is a quiz for the following sections:
// - Strings // - Strings
// - Vecs // - Vecs
// - Move semantics // - Move semantics
// - Modules // - Modules
// - Enums // - Enums
//
// Let's build a little machine in the form of a function. // Let's build a little machine in the form of a function. As input, we're going
// As input, we're going to give a list of strings and commands. These commands // to give a list of strings and commands. These commands determine what action
// determine what action is going to be applied to the string. It can either be: // is going to be applied to the string. It can either be:
// - Uppercase the string // - Uppercase the string
// - Trim the string // - Trim the string
// - Append "bar" to the string a specified amount of times // - Append "bar" to the string a specified amount of times
@ -16,6 +17,7 @@
// - The input is going to be a Vector of a 2-length tuple, // - The input is going to be a Vector of a 2-length tuple,
// the first element is the string, the second one is the command. // the first element is the string, the second one is the command.
// - The output element is going to be a Vector of strings. // - The output element is going to be a Vector of strings.
//
// No hints this time! // No hints this time!
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,17 +1,19 @@
// quiz3.rs // quiz3.rs
//
// This quiz tests: // This quiz tests:
// - Generics // - Generics
// - Traits // - Traits
// An imaginary magical school has a new report card generation system written in Rust! //
// Currently the system only supports creating report cards where the student's grade // An imaginary magical school has a new report card generation system written
// is represented numerically (e.g. 1.0 -> 5.5). // in Rust! Currently the system only supports creating report cards where the
// However, the school also issues alphabetical grades (A+ -> F-) and needs // student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
// to be able to print both types of report card! // school also issues alphabetical grades (A+ -> F-) and needs to be able to
// print both types of report card!
//
// Make the necessary code changes in the struct ReportCard and the impl block // Make the necessary code changes in the struct ReportCard and the impl block
// to support alphabetical report cards. Change the Grade in the second test to "A+" // to support alphabetical report cards. Change the Grade in the second test to
// to show that your changes allow alphabetical grades. // "A+" to show that your changes allow alphabetical grades.
//
// Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,21 +1,24 @@
// arc1.rs // arc1.rs
// In this exercise, we are given a Vec of u32 called "numbers" with values ranging //
// from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] // In this exercise, we are given a Vec of u32 called "numbers" with values
// We would like to use this set of numbers within 8 different threads simultaneously. // ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this
// Each thread is going to get the sum of every eighth value, with an offset. // set of numbers within 8 different threads simultaneously. Each thread is
// going to get the sum of every eighth value, with an offset.
//
// The first thread (offset 0), will sum 0, 8, 16, ... // The first thread (offset 0), will sum 0, 8, 16, ...
// The second thread (offset 1), will sum 1, 9, 17, ... // The second thread (offset 1), will sum 1, 9, 17, ...
// The third thread (offset 2), will sum 2, 10, 18, ... // The third thread (offset 2), will sum 2, 10, 18, ...
// ... // ...
// The eighth thread (offset 7), will sum 7, 15, 23, ... // The eighth thread (offset 7), will sum 7, 15, 23, ...
//
// Because we are using threads, our values need to be thread-safe. Therefore, // Because we are using threads, our values need to be thread-safe. Therefore,
// we are using Arc. We need to make a change in each of the two TODOs. // we are using Arc. We need to make a change in each of the two TODOs.
//
// Make this code compile by filling in a value for `shared_numbers` where the // Make this code compile by filling in a value for `shared_numbers` where the
// first TODO comment is, and create an initial binding for `child_numbers` // first TODO comment is, and create an initial binding for `child_numbers`
// where the second TODO comment is. Try not to create any copies of the `numbers` Vec! // where the second TODO comment is. Try not to create any copies of the
// `numbers` Vec!
//
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,13 +1,15 @@
// box1.rs // box1.rs
// //
// At compile time, Rust needs to know how much space a type takes up. This becomes problematic // At compile time, Rust needs to know how much space a type takes up. This
// for recursive types, where a value can have as part of itself another value of the same type. // becomes problematic for recursive types, where a value can have as part of
// To get around the issue, we can use a `Box` - a smart pointer used to store data on the heap, // itself another value of the same type. To get around the issue, we can use a
// which also allows us to wrap a recursive type. // `Box` - a smart pointer used to store data on the heap, which also allows us
// to wrap a recursive type.
// //
// The recursive type we're implementing in this exercise is the `cons list` - a data structure // The recursive type we're implementing in this exercise is the `cons list` - a
// frequently found in functional programming languages. Each item in a cons list contains two // data structure frequently found in functional programming languages. Each
// elements: the value of the current item and the next item. The last item is a value called `Nil`. // item in a cons list contains two elements: the value of the current item and
// the next item. The last item is a value called `Nil`.
// //
// Step 1: use a `Box` in the enum definition to make the code compile // Step 1: use a `Box` in the enum definition to make the code compile
// Step 2: create both empty and non-empty cons lists by replacing `todo!()` // Step 2: create both empty and non-empty cons lists by replacing `todo!()`

View File

@ -1,12 +1,16 @@
// cow1.rs // cow1.rs
//
// This exercise explores the Cow, or Clone-On-Write type. // This exercise explores the Cow, or Clone-On-Write type. Cow is a
// Cow is a clone-on-write smart pointer. // clone-on-write smart pointer. It can enclose and provide immutable access to
// It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. // borrowed data, and clone the data lazily when mutation or ownership is
// The type is designed to work with general borrowed data via the Borrow trait. // required. The type is designed to work with general borrowed data via the
// Borrow trait.
// //
// This exercise is meant to show you what to expect when passing data to Cow. // This exercise is meant to show you what to expect when passing data to Cow.
// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the TODO markers. // Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the
// TODO markers.
//
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE
@ -50,10 +54,9 @@ mod tests {
#[test] #[test]
fn owned_no_mutation() -> Result<(), &'static str> { fn owned_no_mutation() -> Result<(), &'static str> {
// We can also pass `slice` without `&` so Cow owns it directly. // We can also pass `slice` without `&` so Cow owns it directly. In this
// In this case no mutation occurs and thus also no clone, // case no mutation occurs and thus also no clone, but the result is
// but the result is still owned because it was never borrowed // still owned because it was never borrowed or mutated.
// or mutated.
let slice = vec![0, 1, 2]; let slice = vec![0, 1, 2];
let mut input = Cow::from(slice); let mut input = Cow::from(slice);
match abs_all(&mut input) { match abs_all(&mut input) {
@ -63,9 +66,9 @@ mod tests {
#[test] #[test]
fn owned_mutation() -> Result<(), &'static str> { fn owned_mutation() -> Result<(), &'static str> {
// Of course this is also the case if a mutation does occur. // Of course this is also the case if a mutation does occur. In this
// In this case the call to `to_mut()` returns a reference to // case the call to `to_mut()` returns a reference to the same data as
// the same data as before. // before.
let slice = vec![-1, 0, 1]; let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice); let mut input = Cow::from(slice);
match abs_all(&mut input) { match abs_all(&mut input) {

View File

@ -1,9 +1,14 @@
// rc1.rs // rc1.rs
// In this exercise, we want to express the concept of multiple owners via the Rc<T> type. //
// This is a model of our solar system - there is a Sun type and multiple Planets. // In this exercise, we want to express the concept of multiple owners via the
// The Planets take ownership of the sun, indicating that they revolve around the sun. // Rc<T> type. This is a model of our solar system - there is a Sun type and
// multiple Planets. The Planets take ownership of the sun, indicating that they
// Make this code compile by using the proper Rc primitives to express that the sun has multiple owners. // revolve around the sun.
//
// Make this code compile by using the proper Rc primitives to express that the
// sun has multiple owners.
//
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// strings1.rs // strings1.rs
//
// Make me compile without changing the function signature! // Make me compile without changing the function signature!
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// strings2.rs // strings2.rs
//
// Make me compile without changing the function signature! // Make me compile without changing the function signature!
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// strings3.rs // strings3.rs
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,9 +1,10 @@
// strings4.rs // strings4.rs
//
// Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your // Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your
// task is to call one of these two functions on each value depending on what // task is to call one of these two functions on each value depending on what
// you think each value is. That is, add either `string_slice` or `string` // you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile! // before the parentheses on each line. If you're right, it will compile!
//
// No hints this time! // No hints this time!
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// structs1.rs // structs1.rs
//
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// structs2.rs // structs2.rs
//
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// structs3.rs // structs3.rs
//
// Structs contain data, but can also have logic. In this exercise we have // Structs contain data, but can also have logic. In this exercise we have
// defined the Package struct and we want to test some logic attached to it. // defined the Package struct and we want to test some logic attached to it.
// Make the code compile and the tests pass! // Make the code compile and the tests pass!
// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,11 +1,14 @@
// tests1.rs // tests1.rs
// Tests are important to ensure that your code does what you think it should do. //
// Tests can be run on this file with the following command: // Tests are important to ensure that your code does what you think it should
// rustlings run tests1 // do. Tests can be run on this file with the following command: rustlings run
// tests1
// This test has a problem with it -- make the test compile! Make the test //
// pass! Make the test fail! // This test has a problem with it -- make the test compile! Make the test pass!
// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint. // Make the test fail!
//
// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// tests2.rs // tests2.rs
// This test has a problem with it -- make the test compile! Make the test //
// pass! Make the test fail! // This test has a problem with it -- make the test compile! Make the test pass!
// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint. // Make the test fail!
//
// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// tests3.rs // tests3.rs
//
// This test isn't testing our function -- make it do that in such a way that // This test isn't testing our function -- make it do that in such a way that
// the test passes. Then write a second test that tests whether we get the result // the test passes. Then write a second test that tests whether we get the
// we expect to get when we call `is_even(5)`. // result we expect to get when we call `is_even(5)`.
// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// tests4.rs // tests4.rs
//
// Make sure that we're testing for the correct conditions! // Make sure that we're testing for the correct conditions!
// Execute `rustlings hint tests4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint tests4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,10 +1,12 @@
// threads1.rs // threads1.rs
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a hint. //
// This program spawns multiple threads that each run for at least 250ms, and
// This program spawns multiple threads that each run for at least 250ms, // each thread returns how much time they took to complete. The program should
// and each thread returns how much time they took to complete. // wait until all the spawned threads have finished and should collect their
// The program should wait until all the spawned threads have finished and // return values into a vector.
// should collect their return values into a vector. //
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,11 @@
// threads2.rs // threads2.rs
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a hint. //
// Building on the last exercise, we want all of the threads to complete their work but this time // Building on the last exercise, we want all of the threads to complete their
// the spawned threads need to be in charge of updating a shared value: JobStatus.jobs_completed // work but this time the spawned threads need to be in charge of updating a
// shared value: JobStatus.jobs_completed
//
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE
@ -27,8 +31,9 @@ fn main() {
} }
for handle in handles { for handle in handles {
handle.join().unwrap(); handle.join().unwrap();
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice anything // TODO: Print the value of the JobStatus.jobs_completed. Did you notice
// interesting in the output? Do you have to 'join' on all the handles? // anything interesting in the output? Do you have to 'join' on all the
// handles?
println!("jobs completed {}", ???); println!("jobs completed {}", ???);
} }
} }

View File

@ -1,5 +1,7 @@
// threads3.rs // threads3.rs
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,13 +1,11 @@
// traits1.rs // traits1.rs
// Time to implement some traits!
// //
// Your task is to implement the trait // Time to implement some traits! Your task is to implement the trait
// `AppendBar` for the type `String`. // `AppendBar` for the type `String`. The trait AppendBar has only one function,
// which appends "Bar" to any object implementing this trait.
// //
// The trait AppendBar has only one function, // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a
// which appends "Bar" to any object // hint.
// implementing this trait.
// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,14 +1,11 @@
// traits2.rs // traits2.rs
// //
// Your task is to implement the trait // Your task is to implement the trait `AppendBar` for a vector of strings. To
// `AppendBar` for a vector of strings. // implement this trait, consider for a moment what it means to 'append "Bar"'
//
// To implement this trait, consider for
// a moment what it means to 'append "Bar"'
// to a vector of strings. // to a vector of strings.
// //
// No boiler plate code this time, // No boiler plate code this time, you can do this!
// you can do this! //
// Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,11 +1,12 @@
// traits3.rs // traits3.rs
// //
// Your task is to implement the Licensed trait for // Your task is to implement the Licensed trait for both structures and have
// both structures and have them return the same // them return the same information without writing the same function twice.
// information without writing the same function twice.
// //
// Consider what you can add to the Licensed trait. // Consider what you can add to the Licensed trait.
// Execute `rustlings hint traits3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint traits3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// traits4.rs // traits4.rs
// //
// Your task is to replace the '??' sections so the code compiles. // Your task is to replace the '??' sections so the code compiles.
//
// Don't change any line other than the marked one. // Don't change any line other than the marked one.
// Execute `rustlings hint traits4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint traits4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,8 +1,11 @@
// traits5.rs // traits5.rs
// //
// Your task is to replace the '??' sections so the code compiles. // Your task is to replace the '??' sections so the code compiles.
//
// Don't change any line other than the marked one. // Don't change any line other than the marked one.
// Execute `rustlings hint traits5` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint traits5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,9 @@
// variables1.rs // variables1.rs
//
// Make me compile! // Make me compile!
// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// variables2.rs // variables2.rs
// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// variables3.rs // variables3.rs
// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// variables4.rs // variables4.rs
// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// variables5.rs // variables5.rs
// Execute `rustlings hint variables5` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,5 +1,7 @@
// variables6.rs // variables6.rs
// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a hint. //
// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,7 +1,10 @@
// vecs1.rs // vecs1.rs
// Your task is to create a `Vec` which holds the exact same elements //
// as in the array `a`. // Your task is to create a `Vec` which holds the exact same elements as in the
// array `a`.
//
// Make me compile and pass the test! // Make me compile and pass the test!
//
// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE // I AM NOT DONE

View File

@ -1,6 +1,7 @@
// vecs2.rs // vecs2.rs
// A Vec of even numbers is given. Your task is to complete the loop //
// so that each number in the Vec is multiplied by 2. // A Vec of even numbers is given. Your task is to complete the loop so that
// each number in the Vec is multiplied by 2.
// //
// Make me pass the test! // Make me pass the test!
// //

153
info.toml
View File

@ -287,23 +287,24 @@ Also: Try accessing `vec0` after having called `fill_vec()`. See what happens!""
[[exercises]] [[exercises]]
name = "move_semantics2" name = "move_semantics2"
path = "exercises/move_semantics/move_semantics2.rs" path = "exercises/move_semantics/move_semantics2.rs"
mode = "compile" mode = "test"
hint = """ hint = """
So, `vec0` is passed into the `fill_vec` function as an argument. In Rust, When running this exercise for the first time, you'll notice an error about
when an argument is passed to a function and it's not explicitly returned, "borrow of moved value". In Rust, when an argument is passed to a function and
you can't use the original variable anymore. We call this "moving" a variable. it's not explicitly returned, you can't use the original variable anymore.
Variables that are moved into a function (or block scope) and aren't explicitly We call this "moving" a variable. When we pass `vec0` into `fill_vec`, it's being
returned get "dropped" at the end of that function. This is also what happens here. "moved" into `vec1`, meaning we can't access `vec0` anymore after the fact.
There's a few ways to fix this, try them all if you want: Rust provides a couple of different ways to mitigate this issue, feel free to try them all:
1. Make another, separate version of the data that's in `vec0` and pass that 1. You could make another, separate version of the data that's in `vec0` and pass that
to `fill_vec` instead. to `fill_vec` instead.
2. Make `fill_vec` borrow its argument instead of taking ownership of it, 2. Make `fill_vec` borrow its argument instead of taking ownership of it,
and then copy the data within the function in order to return an owned and then copy the data within the function (`vec.clone()`) in order to return an owned
`Vec<i32>` `Vec<i32>`.
3. Make `fill_vec` *mutably* borrow a reference to its argument (which will need to be 3. Or, you could make `fill_vec` *mutably* borrow a reference to its argument (which will need to be
mutable), modify it directly, then not return anything. Then you can get rid mutable), modify it directly, then not return anything. This means that `vec0` will change over the
of `vec1` entirely -- note that this will change what gets printed by the course of the function, and makes `vec1` redundant (make sure to change the parameters of the `println!`
first `println!`""" statements if you go this route)
"""
[[exercises]] [[exercises]]
name = "move_semantics3" name = "move_semantics3"
@ -905,67 +906,6 @@ The fold method can be useful in the count_collection_iterator function.
For a further challenge, consult the documentation for Iterator to find For a further challenge, consult the documentation for Iterator to find
a different method that could make your code more compact than using fold.""" a different method that could make your code more compact than using fold."""
# THREADS
[[exercises]]
name = "threads1"
path = "exercises/threads/threads1.rs"
mode = "compile"
hint = """
`JoinHandle` is a struct that is returned from a spawned thread:
https://doc.rust-lang.org/std/thread/fn.spawn.html
A challenge with multi-threaded applications is that the main thread can
finish before the spawned threads are completed.
https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish-using-join-handles
Use the JoinHandles to wait for each thread to finish and collect their results.
https://doc.rust-lang.org/std/thread/struct.JoinHandle.html
"""
[[exercises]]
name = "threads2"
path = "exercises/threads/threads2.rs"
mode = "compile"
hint = """
`Arc` is an Atomic Reference Counted pointer that allows safe, shared access
to **immutable** data. But we want to *change* the number of `jobs_completed`
so we'll need to also use another type that will only allow one thread to
mutate the data at a time. Take a look at this section of the book:
https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct
and keep reading if you'd like more hints :)
Do you now have an `Arc` `Mutex` `JobStatus` at the beginning of main? Like:
`let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));`
Similar to the code in the example in the book that happens after the text
that says "We can use Arc<T> to fix this.". If not, give that a try! If you
do and would like more hints, keep reading!!
Make sure neither of your threads are holding onto the lock of the mutex
while they are sleeping, since this will prevent the other thread from
being allowed to get the lock. Locks are automatically released when
they go out of scope.
If you've learned from the sample solutions, I encourage you to come
back to this exercise and try it again in a few days to reinforce
what you've learned :)"""
[[exercises]]
name = "threads3"
path = "exercises/threads/threads3.rs"
mode = "compile"
hint = """
An alternate way to handle concurrency between threads is to use
a mpsc (multiple producer, single consumer) channel to communicate.
With both a sending end and a receiving end, it's possible to
send values in one thread and receive them in another.
Multiple producers are possible by using clone() to create a duplicate
of the original sending end.
See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info.
"""
# SMART POINTERS # SMART POINTERS
[[exercises]] [[exercises]]
@ -1028,6 +968,67 @@ Check out https://doc.rust-lang.org/std/borrow/enum.Cow.html for documentation
on the `Cow` type. on the `Cow` type.
""" """
# THREADS
[[exercises]]
name = "threads1"
path = "exercises/threads/threads1.rs"
mode = "compile"
hint = """
`JoinHandle` is a struct that is returned from a spawned thread:
https://doc.rust-lang.org/std/thread/fn.spawn.html
A challenge with multi-threaded applications is that the main thread can
finish before the spawned threads are completed.
https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish-using-join-handles
Use the JoinHandles to wait for each thread to finish and collect their results.
https://doc.rust-lang.org/std/thread/struct.JoinHandle.html
"""
[[exercises]]
name = "threads2"
path = "exercises/threads/threads2.rs"
mode = "compile"
hint = """
`Arc` is an Atomic Reference Counted pointer that allows safe, shared access
to **immutable** data. But we want to *change* the number of `jobs_completed`
so we'll need to also use another type that will only allow one thread to
mutate the data at a time. Take a look at this section of the book:
https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct
and keep reading if you'd like more hints :)
Do you now have an `Arc` `Mutex` `JobStatus` at the beginning of main? Like:
`let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));`
Similar to the code in the example in the book that happens after the text
that says "We can use Arc<T> to fix this.". If not, give that a try! If you
do and would like more hints, keep reading!!
Make sure neither of your threads are holding onto the lock of the mutex
while they are sleeping, since this will prevent the other thread from
being allowed to get the lock. Locks are automatically released when
they go out of scope.
If you've learned from the sample solutions, I encourage you to come
back to this exercise and try it again in a few days to reinforce
what you've learned :)"""
[[exercises]]
name = "threads3"
path = "exercises/threads/threads3.rs"
mode = "compile"
hint = """
An alternate way to handle concurrency between threads is to use
a mpsc (multiple producer, single consumer) channel to communicate.
With both a sending end and a receiving end, it's possible to
send values in one thread and receive them in another.
Multiple producers are possible by using clone() to create a duplicate
of the original sending end.
See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info.
"""
# MACROS # MACROS
[[exercises]] [[exercises]]
@ -1170,4 +1171,4 @@ name = "as_ref_mut"
path = "exercises/conversions/as_ref_mut.rs" path = "exercises/conversions/as_ref_mut.rs"
mode = "test" mode = "test"
hint = """ hint = """
Add AsRef<str> as a trait bound to the functions.""" Add AsRef<str> or AsMut<u32> as a trait bound to the functions."""