Compare commits

..

No commits in common. "main" and "all-contributors/add-hyperparabolic" have entirely different histories.

58 changed files with 669 additions and 354 deletions

View file

@ -884,33 +884,6 @@
"contributions": [ "contributions": [
"code" "code"
] ]
},
{
"login": "kolbma",
"name": "arlecchino",
"avatar_url": "https://avatars.githubusercontent.com/u/5228369?v=4",
"profile": "https://www.net4visions.at",
"contributions": [
"doc"
]
},
{
"login": "jazzplato",
"name": "Richthofen",
"avatar_url": "https://avatars.githubusercontent.com/u/7576730?v=4",
"profile": "https://richthofen.io/",
"contributions": [
"code"
]
},
{
"login": "cseltol",
"name": "Ivan Nerazumov",
"avatar_url": "https://avatars.githubusercontent.com/u/64264529?v=4",
"profile": "https://github.com/cseltol",
"contributions": [
"doc"
]
} }
], ],
"contributorsPerLine": 8, "contributorsPerLine": 8,

295
README.md
View file

@ -1,3 +1,294 @@
# rustlings <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-95-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
My solutions to rustlings excercises # rustlings 🦀❤️
Greetings and welcome to `rustlings`. This project contains small exercises to get you used to reading and writing Rust code. This includes reading and responding to compiler messages!
_...looking for the old, web-based version of Rustlings? Try [here](https://github.com/rust-lang/rustlings/tree/rustlings-1)_
Alternatively, for a first-time Rust learner, there are several other resources:
- [The Book](https://doc.rust-lang.org/book/index.html) - The most comprehensive resource for learning Rust, but a bit theoretical sometimes. You will be using this along with Rustlings!
- [Rust By Example](https://doc.rust-lang.org/rust-by-example/index.html) - Learn Rust by solving little exercises! It's almost like `rustlings`, but online
## Getting Started
_Note: If you're on MacOS, make sure you've installed Xcode and its developer tools by typing `xcode-select --install`._
You will need to have Rust installed. You can get it by visiting https://rustup.rs. This'll also install Cargo, Rust's package/project manager.
## MacOS/Linux
Just run:
```bash
curl -L https://git.io/install-rustlings | bash
# Or if you want it to be installed to a different path:
curl -L https://git.io/install-rustlings | bash -s mypath/
```
This will install Rustlings and give you access to the `rustlings` command. Run it to get started!
## Windows
In PowerShell (Run as Administrator), set `ExecutionPolicy` to `RemoteSigned`:
```ps
Set-ExecutionPolicy RemoteSigned
```
Then, you can run:
```ps
Start-BitsTransfer -Source https://git.io/JTL5v -Destination $env:TMP/install_rustlings.ps1; Unblock-File $env:TMP/install_rustlings.ps1; Invoke-Expression $env:TMP/install_rustlings.ps1
```
To install Rustlings. Same as on MacOS/Linux, you will have access to the `rustlings` command after it.
When you get a permission denied message then you have to exclude the directory where you placed the rustlings in your virus-scanner
## Browser:
[Run on Repl.it](https://repl.it/github/rust-lang/rustlings)
[Open in Gitpod](https://gitpod.io/#https://github.com/rust-lang/rustlings)
## Manually
Basically: Clone the repository, checkout to the latest tag, run `cargo install`.
```bash
git clone https://github.com/rust-lang/rustlings
cd rustlings
git checkout tags/4.4.0 # or whatever the latest version is (find out at https://github.com/rust-lang/rustlings/releases/latest)
cargo install --force --path .
```
If there are installation errors, ensure that your toolchain is up to date. For the latest, run:
```bash
rustup update
```
Then, same as above, run `rustlings` to get started.
## Doing exercises
The exercises are sorted by topic and can be found in the subdirectory `rustlings/exercises/<topic>`. For every topic there is an additional README file with some resources to get you started on the topic. We really recommend that you have a look at them before you start.
The task is simple. Most exercises contain an error that keeps them from compiling, and it's up to you to fix it! Some exercises are also run as tests, but rustlings handles them all the same. To run the exercises in the recommended order, execute:
```bash
rustlings watch
```
This will try to verify the completion of every exercise in a predetermined order (what we think is best for newcomers). It will also rerun automatically every time you change a file in the `exercises/` directory. If you want to only run it once, you can use:
```bash
rustlings verify
```
This will do the same as watch, but it'll quit after running.
In case you want to go by your own order, or want to only verify a single exercise, you can run:
```bash
rustlings run myExercise1
```
In case you get stuck, you can run the following command to get a hint for your
exercise:
``` bash
rustlings hint myExercise1
```
To check your progress, you can run the following command:
```bash
rustlings list
```
## Testing yourself
After every couple of sections, there will be a quiz that'll test your knowledge on a bunch of sections at once. These quizzes are found in `exercises/quizN.rs`.
## Continuing On
Once you've completed Rustlings, put your new knowledge to good use! Continue practicing your Rust skills by building your own projects, contributing to Rustlings, or finding other open-source projects to contribute to.
## Uninstalling Rustlings
If you want to remove Rustlings from your system, there's two steps. First, you'll need to remove the exercises folder that the install script created
for you:
``` bash
rm -rf rustlings # or your custom folder name, if you chose and or renamed it
```
Second, since Rustlings got installed via `cargo install`, it's only reasonable to assume that you can also remove it using Cargo, and
exactly that is the case. Run `cargo uninstall` to remove the `rustlings` binary:
``` bash
cargo uninstall rustlings
```
Now you should be done!
## Completion
Rustlings isn't done; there are a couple of sections that are very experimental and don't have proper documentation. These include:
- Errors (`exercises/errors/`)
- Option (`exercises/option/`)
- Result (`exercises/result/`)
- Move Semantics (could still be improved, `exercises/move_semantics/`)
Additionally, we could use exercises on a couple of topics:
- Structs
- Better ownership stuff
- `impl`
- ??? probably more
If you are interested in improving or adding new ones, please feel free to contribute! Read on for more information :)
## Contributing
See [CONTRIBUTING.md](./CONTRIBUTING.md).
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="http://carol-nichols.com"><img src="https://avatars2.githubusercontent.com/u/193874?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Carol (Nichols &#124;&#124; Goulding)</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=carols10cents" title="Code">💻</a> <a href="#content-carols10cents" title="Content">🖋</a></td>
<td align="center"><a href="https://twitter.com/QuietMisdreavus"><img src="https://avatars2.githubusercontent.com/u/5217170?v=4?s=100" width="100px;" alt=""/><br /><sub><b>QuietMisdreavus</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=QuietMisdreavus" title="Code">💻</a> <a href="#content-QuietMisdreavus" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/robertlugg"><img src="https://avatars0.githubusercontent.com/u/6054540?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Robert M Lugg</b></sub></a><br /><a href="#content-robertlugg" title="Content">🖋</a></td>
<td align="center"><a href="https://hynek.me/about/"><img src="https://avatars3.githubusercontent.com/u/41240?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hynek Schlawack</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=hynek" title="Code">💻</a></td>
<td align="center"><a href="https://spacekookie.de"><img src="https://avatars0.githubusercontent.com/u/7669898?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Katharina Fey</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=spacekookie" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/lukabavdaz"><img src="https://avatars0.githubusercontent.com/u/9624558?v=4?s=100" width="100px;" alt=""/><br /><sub><b>lukabavdaz</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=lukabavdaz" title="Code">💻</a> <a href="#content-lukabavdaz" title="Content">🖋</a></td>
<td align="center"><a href="http://vestera.as"><img src="https://avatars2.githubusercontent.com/u/4187449?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Erik Vesteraas</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=evestera" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/Delet0r"><img src="https://avatars1.githubusercontent.com/u/23195618?v=4?s=100" width="100px;" alt=""/><br /><sub><b>delet0r</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=Delet0r" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="http://phinary.ca"><img src="https://avatars1.githubusercontent.com/u/10522375?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shaun Bennett</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=shaunbennett" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/abagshaw"><img src="https://avatars2.githubusercontent.com/u/8594541?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andrew Bagshaw</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=abagshaw" title="Code">💻</a></td>
<td align="center"><a href="https://ai6ua.net/"><img src="https://avatars2.githubusercontent.com/u/175578?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kyle Isom</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=kisom" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/ColinPitrat"><img src="https://avatars3.githubusercontent.com/u/1541863?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Colin Pitrat</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=ColinPitrat" title="Code">💻</a></td>
<td align="center"><a href="https://zacanger.com"><img src="https://avatars3.githubusercontent.com/u/12520493?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Zac Anger</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=zacanger" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/mgeier"><img src="https://avatars1.githubusercontent.com/u/705404?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Matthias Geier</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=mgeier" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/cjpearce"><img src="https://avatars1.githubusercontent.com/u/3453268?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Chris Pearce</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=cjpearce" title="Code">💻</a></td>
<td align="center"><a href="https://yvan-sraka.github.io"><img src="https://avatars2.githubusercontent.com/u/705213?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yvan Sraka</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=yvan-sraka" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/dendi239"><img src="https://avatars3.githubusercontent.com/u/16478650?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Denys Smirnov</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=dendi239" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/eddyp"><img src="https://avatars2.githubusercontent.com/u/123772?v=4?s=100" width="100px;" alt=""/><br /><sub><b>eddyp</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=eddyp" title="Code">💻</a></td>
<td align="center"><a href="http://about.me/BrianKung"><img src="https://avatars1.githubusercontent.com/u/2836167?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Brian Kung</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=briankung" title="Code">💻</a> <a href="#content-briankung" title="Content">🖋</a></td>
<td align="center"><a href="https://rcousineau.gitlab.io"><img src="https://avatars3.githubusercontent.com/u/281039?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Russell</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=miller-time" title="Code">💻</a></td>
<td align="center"><a href="http://danwilhelm.com"><img src="https://avatars3.githubusercontent.com/u/6137185?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dan Wilhelm</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=danwilhelm" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/Jesse-Cameron"><img src="https://avatars3.githubusercontent.com/u/3723654?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jesse</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=Jesse-Cameron" title="Code">💻</a> <a href="#content-Jesse-Cameron" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/MrFroop"><img src="https://avatars3.githubusercontent.com/u/196700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fredrik Jambrén</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=MrFroop" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/petemcfarlane"><img src="https://avatars3.githubusercontent.com/u/3472717?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pete McFarlane</b></sub></a><br /><a href="#content-petemcfarlane" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/nkanderson"><img src="https://avatars0.githubusercontent.com/u/4128825?v=4?s=100" width="100px;" alt=""/><br /><sub><b>nkanderson</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=nkanderson" title="Code">💻</a> <a href="#content-nkanderson" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/ajaxm"><img src="https://avatars0.githubusercontent.com/u/13360138?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ajax M</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=ajaxm" title="Documentation">📖</a></td>
<td align="center"><a href="https://dylnuge.com"><img src="https://avatars2.githubusercontent.com/u/118624?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dylan Nugent</b></sub></a><br /><a href="#content-Dylnuge" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/vyaslav"><img src="https://avatars0.githubusercontent.com/u/1385427?v=4?s=100" width="100px;" alt=""/><br /><sub><b>vyaslav</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=vyaslav" title="Code">💻</a> <a href="#content-vyaslav" title="Content">🖋</a></td>
<td align="center"><a href="https://join.sfxd.org"><img src="https://avatars1.githubusercontent.com/u/17297466?v=4?s=100" width="100px;" alt=""/><br /><sub><b>George</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=gdoenlen" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/nyxtom"><img src="https://avatars2.githubusercontent.com/u/222763?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Thomas Holloway</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=nyxtom" title="Code">💻</a> <a href="#content-nyxtom" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/workingjubilee"><img src="https://avatars1.githubusercontent.com/u/46493976?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jubilee</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=workingjubilee" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/WofWca"><img src="https://avatars1.githubusercontent.com/u/39462442?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WofWca</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=WofWca" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/jrvidal"><img src="https://avatars0.githubusercontent.com/u/1636604?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Roberto Vidal</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=jrvidal" title="Code">💻</a> <a href="https://github.com/rust-lang/rustlings/commits?author=jrvidal" title="Documentation">📖</a> <a href="#ideas-jrvidal" title="Ideas, Planning, & Feedback">🤔</a> <a href="#maintenance-jrvidal" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/jensim"><img src="https://avatars0.githubusercontent.com/u/3663856?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jens</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=jensim" title="Documentation">📖</a></td>
<td align="center"><a href="http://rahatah.me/d"><img src="https://avatars3.githubusercontent.com/u/3174006?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rahat Ahmed</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=rahatarmanahmed" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/AbdouSeck"><img src="https://avatars2.githubusercontent.com/u/6490055?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Abdou Seck</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=AbdouSeck" title="Code">💻</a> <a href="#content-AbdouSeck" title="Content">🖋</a> <a href="https://github.com/rust-lang/rustlings/pulls?q=is%3Apr+reviewed-by%3AAbdouSeck" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="https://codehearts.com"><img src="https://avatars0.githubusercontent.com/u/2885412?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Katie</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=codehearts" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/Socratides"><img src="https://avatars3.githubusercontent.com/u/27732983?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Socrates</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=Socratides" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/gnodarse"><img src="https://avatars3.githubusercontent.com/u/46761795?v=4?s=100" width="100px;" alt=""/><br /><sub><b>gnodarse</b></sub></a><br /><a href="#content-gnodarse" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/harrisonmetz"><img src="https://avatars1.githubusercontent.com/u/7883408?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Harrison Metzger</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=harrisonmetz" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/TorbenJ"><img src="https://avatars2.githubusercontent.com/u/9077102?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Torben Jonas</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=TorbenJ" title="Code">💻</a> <a href="#content-TorbenJ" title="Content">🖋</a></td>
<td align="center"><a href="http://paulbissex.com/"><img src="https://avatars0.githubusercontent.com/u/641?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Paul Bissex</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=pbx" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/sjmann"><img src="https://avatars0.githubusercontent.com/u/6589896?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Steven Mann</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=sjmann" title="Code">💻</a> <a href="#content-sjmann" title="Content">🖋</a></td>
<td align="center"><a href="https://smmdb.net/"><img src="https://avatars2.githubusercontent.com/u/5855071?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mario Reder</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=Tarnadas" title="Code">💻</a> <a href="#content-Tarnadas" title="Content">🖋</a></td>
<td align="center"><a href="https://keybase.io/skim"><img src="https://avatars0.githubusercontent.com/u/47347?v=4?s=100" width="100px;" alt=""/><br /><sub><b>skim</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=sl4m" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/sanjaykdragon"><img src="https://avatars1.githubusercontent.com/u/10261698?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sanjay K</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=sanjaykdragon" title="Code">💻</a> <a href="#content-sanjaykdragon" title="Content">🖋</a></td>
<td align="center"><a href="http://www.rohanjain.in"><img src="https://avatars1.githubusercontent.com/u/343499?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rohan Jain</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=crodjer" title="Code">💻</a></td>
<td align="center"><a href="https://www.saidaspen.se"><img src="https://avatars1.githubusercontent.com/u/7727687?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Said Aspen</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=saidaspen" title="Code">💻</a> <a href="#content-saidaspen" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/uce"><img src="https://avatars3.githubusercontent.com/u/1756620?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ufuk Celebi</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=uce" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/lebedevsergey"><img src="https://avatars2.githubusercontent.com/u/7325764?v=4?s=100" width="100px;" alt=""/><br /><sub><b>lebedevsergey</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=lebedevsergey" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/avrong"><img src="https://avatars2.githubusercontent.com/u/6342851?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aleksei Trifonov</b></sub></a><br /><a href="#content-avrong" title="Content">🖋</a></td>
<td align="center"><a href="https://drn.ie"><img src="https://avatars2.githubusercontent.com/u/411136?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Darren Meehan</b></sub></a><br /><a href="#content-Darrenmeehan" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/jihchi"><img src="https://avatars1.githubusercontent.com/u/87983?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jihchi Lee</b></sub></a><br /><a href="#content-jihchi" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/bertonha"><img src="https://avatars3.githubusercontent.com/u/1225902?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christofer Bertonha</b></sub></a><br /><a href="#content-bertonha" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/apatniv"><img src="https://avatars2.githubusercontent.com/u/22565917?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vivek Bharath Akupatni</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=apatniv" title="Code">💻</a> <a href="https://github.com/rust-lang/rustlings/commits?author=apatniv" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/DiD92"><img src="https://avatars3.githubusercontent.com/u/6002416?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dídac Sementé Fernández</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=DiD92" title="Code">💻</a> <a href="#content-DiD92" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/wrobstory"><img src="https://avatars3.githubusercontent.com/u/2601457?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rob Story</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=wrobstory" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/siobhanjacobson"><img src="https://avatars2.githubusercontent.com/u/28983835?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Siobhan Jacobson</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=siobhanjacobson" title="Code">💻</a></td>
<td align="center"><a href="https://www.linkedin.com/in/evancarroll/"><img src="https://avatars2.githubusercontent.com/u/19922?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evan Carroll</b></sub></a><br /><a href="#content-EvanCarroll" title="Content">🖋</a></td>
<td align="center"><a href="http://www.jawaadmahmood.com"><img src="https://avatars3.githubusercontent.com/u/95606?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jawaad Mahmood</b></sub></a><br /><a href="#content-jmahmood" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/GaurangTandon"><img src="https://avatars1.githubusercontent.com/u/6308683?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gaurang Tandon</b></sub></a><br /><a href="#content-GaurangTandon" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/dev-cyprium"><img src="https://avatars1.githubusercontent.com/u/6002628?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stefan Kupresak</b></sub></a><br /><a href="#content-dev-cyprium" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/greg-el"><img src="https://avatars3.githubusercontent.com/u/45019882?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Greg Leonard</b></sub></a><br /><a href="#content-greg-el" title="Content">🖋</a></td>
<td align="center"><a href="https://ryanpcmcquen.org"><img src="https://avatars3.githubusercontent.com/u/772937?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ryan McQuen</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=ryanpcmcquen" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/AnnikaCodes"><img src="https://avatars3.githubusercontent.com/u/56906084?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Annika</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/pulls?q=is%3Apr+reviewed-by%3AAnnikaCodes" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="https://darnuria.eu"><img src="https://avatars1.githubusercontent.com/u/2827553?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Axel Viala</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=darnuria" title="Code">💻</a></td>
<td align="center"><a href="https://sazid.github.io"><img src="https://avatars1.githubusercontent.com/u/2370167?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mohammed Sazid Al Rashid</b></sub></a><br /><a href="#content-sazid" title="Content">🖋</a> <a href="https://github.com/rust-lang/rustlings/commits?author=sazid" title="Code">💻</a></td>
<td align="center"><a href="https://codingthemsoftly.com"><img src="https://avatars1.githubusercontent.com/u/17479099?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Caleb Webber</b></sub></a><br /><a href="#maintenance-seeplusplus" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/pcn"><img src="https://avatars2.githubusercontent.com/u/1056756?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Peter N</b></sub></a><br /><a href="#maintenance-pcn" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/seancad"><img src="https://avatars1.githubusercontent.com/u/47405611?v=4?s=100" width="100px;" alt=""/><br /><sub><b>seancad</b></sub></a><br /><a href="#maintenance-seancad" title="Maintenance">🚧</a></td>
<td align="center"><a href="http://willhayworth.com"><img src="https://avatars3.githubusercontent.com/u/181174?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Will Hayworth</b></sub></a><br /><a href="#content-wsh" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/chrizel"><img src="https://avatars3.githubusercontent.com/u/20802?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christian Zeller</b></sub></a><br /><a href="#content-chrizel" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/jfchevrette"><img src="https://avatars.githubusercontent.com/u/3001?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jean-Francois Chevrette</b></sub></a><br /><a href="#content-jfchevrette" title="Content">🖋</a> <a href="https://github.com/rust-lang/rustlings/commits?author=jfchevrette" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jbaber"><img src="https://avatars.githubusercontent.com/u/1908117?v=4?s=100" width="100px;" alt=""/><br /><sub><b>John Baber-Lucero</b></sub></a><br /><a href="#content-jbaber" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/tal-zvon"><img src="https://avatars.githubusercontent.com/u/3195851?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tal</b></sub></a><br /><a href="#content-tal-zvon" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/apogeeoak"><img src="https://avatars.githubusercontent.com/u/59737221?v=4?s=100" width="100px;" alt=""/><br /><sub><b>apogeeoak</b></sub></a><br /><a href="#content-apogeeoak" title="Content">🖋</a> <a href="https://github.com/rust-lang/rustlings/commits?author=apogeeoak" title="Code">💻</a></td>
<td align="center"><a href="http://www.garfieldtech.com/"><img src="https://avatars.githubusercontent.com/u/254863?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Larry Garfield</b></sub></a><br /><a href="#content-Crell" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/circumspect"><img src="https://avatars.githubusercontent.com/u/40770208?v=4?s=100" width="100px;" alt=""/><br /><sub><b>circumspect</b></sub></a><br /><a href="#content-circumspect" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/cjwyett"><img src="https://avatars.githubusercontent.com/u/34195737?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cyrus Wyett</b></sub></a><br /><a href="#content-cjwyett" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/cadolphs"><img src="https://avatars.githubusercontent.com/u/13894820?v=4?s=100" width="100px;" alt=""/><br /><sub><b>cadolphs</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=cadolphs" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://www.haveneer.com"><img src="https://avatars.githubusercontent.com/u/26146722?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pascal H.</b></sub></a><br /><a href="#content-hpwxf" title="Content">🖋</a></td>
<td align="center"><a href="https://twitter.com/chapeupreto"><img src="https://avatars.githubusercontent.com/u/834048?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rod Elias</b></sub></a><br /><a href="#content-chapeupreto" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/blerchy"><img src="https://avatars.githubusercontent.com/u/2555355?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Matt Lebl</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=blerchy" title="Code">💻</a></td>
<td align="center"><a href="http://flakolefluk.dev"><img src="https://avatars.githubusercontent.com/u/11986564?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ignacio Le Fluk</b></sub></a><br /><a href="#content-flakolefluk" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/tlyu"><img src="https://avatars.githubusercontent.com/u/431873?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Taylor Yu</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=tlyu" title="Code">💻</a> <a href="#content-tlyu" title="Content">🖋</a></td>
<td align="center"><a href="https://zerotask.github.io"><img src="https://avatars.githubusercontent.com/u/20150243?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Patrick Hintermayer</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=Zerotask" title="Code">💻</a></td>
<td align="center"><a href="https://petkopavlovski.com/"><img src="https://avatars.githubusercontent.com/u/32264020?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pete Pavlovski</b></sub></a><br /><a href="#content-arthas168" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/k12ish"><img src="https://avatars.githubusercontent.com/u/45272873?v=4?s=100" width="100px;" alt=""/><br /><sub><b>k12ish</b></sub></a><br /><a href="#content-k12ish" title="Content">🖋</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/hongshaoyang"><img src="https://avatars.githubusercontent.com/u/19281800?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shao Yang Hong</b></sub></a><br /><a href="#content-hongshaoyang" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/bmacer"><img src="https://avatars.githubusercontent.com/u/13931806?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Brandon Macer</b></sub></a><br /><a href="#content-bmacer" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/stoiandan"><img src="https://avatars.githubusercontent.com/u/10388612?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stoian Dan</b></sub></a><br /><a href="#content-stoiandan" title="Content">🖋</a></td>
<td align="center"><a href="https://about.me/pjdelport"><img src="https://avatars.githubusercontent.com/u/630271?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pi Delport</b></sub></a><br /><a href="#content-PiDelport" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/sateeshkumarb"><img src="https://avatars.githubusercontent.com/u/429263?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sateesh </b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=sateeshkumarb" title="Code">💻</a> <a href="#content-sateeshkumarb" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/kayuapi"><img src="https://avatars.githubusercontent.com/u/10304328?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ZC</b></sub></a><br /><a href="#content-kayuapi" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/hyperparabolic"><img src="https://avatars.githubusercontent.com/u/12348474?v=4?s=100" width="100px;" alt=""/><br /><sub><b>hyperparabolic</b></sub></a><br /><a href="https://github.com/rust-lang/rustlings/commits?author=hyperparabolic" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

View file

@ -11,18 +11,18 @@
// Execute the command `rustlings hint hashmap1` if you need // Execute the command `rustlings hint hashmap1` if you need
// hints. // hints.
// I AM NOT DONE
use std::collections::HashMap; use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> { fn fruit_basket() -> HashMap<String, u32> {
let mut basket = HashMap::new(); // TODO: declare your hash map here. let mut basket = // TODO: declare your hash map here.
// Two bananas are already given for you :) // Two bananas are already given for you :)
basket.insert(String::from("banana"), 2); basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket here. // TODO: Put more fruits in your basket here.
basket.insert(String::from("peach"), 2);
basket.insert(String::from("mango"), 2);
basket.insert(String::from("apple"), 2);
basket basket
} }

View file

@ -12,6 +12,8 @@
// Execute the command `rustlings hint hashmap2` if you need // Execute the command `rustlings hint hashmap2` if you need
// hints. // hints.
// I AM NOT DONE
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)] #[derive(Hash, PartialEq, Eq)]
@ -33,9 +35,9 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
]; ];
for fruit in fruit_kinds { for fruit in fruit_kinds {
if fruit == Fruit::Banana || fruit == Fruit::Pineapple { // TODO: Put new fruits if not already present. Note that you
basket.insert(fruit, 4); // are not allowed to put any type of fruit that's already
} // present!
} }
} }

View file

@ -4,9 +4,11 @@
// Make me compile and pass the test! // Make me compile and pass the test!
// Execute the command `rustlings hint vec1` if you need hints. // Execute the command `rustlings hint vec1` if you need hints.
// I AM NOT DONE
fn array_and_vec() -> ([i32; 4], Vec<i32>) { fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array let a = [10, 20, 30, 40]; // a plain array
let v = vec![10,20,30,40]; // TODO: declare your vector here with the macro for vectors let v = // TODO: declare your vector here with the macro for vectors
(a, v) (a, v)
} }

View file

@ -7,14 +7,12 @@
// Execute the command `rustlings hint vec2` if you need // Execute the command `rustlings hint vec2` if you need
// hints. // hints.
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> { fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() { for i in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is // TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2. // multiplied by 2.
// *i accesses a specific object in vector?
// *= 2 multiplies it by 2
*i *= 2;
} }
// At this point, `v` should be equal to [4, 8, 12, 16, 20]. // At this point, `v` should be equal to [4, 8, 12, 16, 20].

View file

@ -1,12 +1,11 @@
// enums1.rs // enums1.rs
// Make me compile! Execute `rustlings hint enums1` for hints! // Make me compile! Execute `rustlings hint enums1` for hints!
// I AM NOT DONE
#[derive(Debug)] #[derive(Debug)]
enum Message { enum Message {
Quit, // TODO: define a few types of messages as used below
Echo,
Move,
ChangeColor
} }
fn main() { fn main() {

View file

@ -1,12 +1,11 @@
// enums2.rs // enums2.rs
// Make me compile! Execute `rustlings hint enums2` for hints! // Make me compile! Execute `rustlings hint enums2` for hints!
// I AM NOT DONE
#[derive(Debug)] #[derive(Debug)]
enum Message { enum Message {
Move { x: i32, y: i32 }, // TODO: define the different variants used below
Echo(String),
ChangeColor(i32,i32,i32),
Quit
} }
impl Message { impl Message {

View file

@ -1,11 +1,10 @@
// enums3.rs // enums3.rs
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// I AM NOT DONE
enum Message { enum Message {
Move(Point), // TODO: implement the message variant types based on their usage below
Echo(String),
ChangeColor((u8,u8,u8)),
Quit
} }
struct Point { struct Point {
@ -38,13 +37,6 @@ impl State {
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 variants
match message {
Message::ChangeColor((r,g,b)) => self.change_color((r,g,b)),
Message::Echo(String) => self.echo(String),
Message::Move(Pointer) => self.move_position(Pointer),
Message::Quit => self.quit(),
_ => panic!("NOTHING SUPPLIED D:"),
}
} }
} }

View file

@ -6,12 +6,14 @@
// this function to have. // this function to have.
// Execute `rustlings hint errors1` for hints! // Execute `rustlings hint errors1` for hints!
pub fn generate_nametag_text(name: String) -> Result<String, String> { // I AM NOT DONE
pub fn generate_nametag_text(name: String) -> Option<String> {
if name.len() > 0 { if name.len() > 0 {
Ok(format!("Hi! My name is {}", name)) Some(format!("Hi! My name is {}", name))
} else { } else {
// Empty names aren't allowed. // Empty names aren't allowed.
Err("Empty names aren't allowed.".to_owned()) None
} }
} }
@ -26,12 +28,11 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() { fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!( assert_eq!(
generate_nametag_text("Beyoncé".into()), generate_nametag_text("Beyoncé".into()),
Ok("Hi! My name is Beyoncé".into()) Some("Hi! My name is Beyoncé".into())
); );
} }
#[test] #[test]
#[should_panic]
fn explains_why_generating_nametag_text_fails() { fn explains_why_generating_nametag_text_fails() {
assert_eq!( assert_eq!(
generate_nametag_text("".into()), generate_nametag_text("".into()),

View file

@ -16,12 +16,14 @@
// There are at least two ways to implement this that are both correct-- but // There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways. // one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1; let processing_fee = 1;
let cost_per_item = 5; let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?; let qty = item_quantity.parse::<i32>();
Ok(qty * cost_per_item + processing_fee) Ok(qty * cost_per_item + processing_fee)
} }

View file

@ -4,12 +4,11 @@
// Why not? What should we do to fix it? // Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints! // Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
// In previous excercises we were taught that Result can output fn main() {
// i32 and ParseIntError, but nobody told us that Result can also
// output () instead of i32... oops
fn main() -> Result<(), ParseIntError> {
let mut tokens = 100; let mut tokens = 100;
let pretend_user_input = "8"; let pretend_user_input = "8";
@ -21,8 +20,6 @@ fn main() -> Result<(), ParseIntError> {
tokens -= cost; tokens -= cost;
println!("You now have {} tokens.", tokens); println!("You now have {} tokens.", tokens);
} }
// No need for Err() because `?` operator already handles it well
Ok(())
} }
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {

View file

@ -1,5 +1,5 @@
// result1.rs // errors4.rs
// Make this test pass! Execute `rustlings hint result1` for hints :) // Make this test pass! Execute `rustlings hint errors4` for hints :)
// I AM NOT DONE // I AM NOT DONE

View file

@ -0,0 +1,53 @@
// errors5.rs
// This program uses a completed version of the code from errors4.
// It won't compile right now! Why?
// Execute `rustlings hint errors5` for hints!
// I AM NOT DONE
use std::error;
use std::fmt;
use std::num::ParseIntError;
// TODO: update the return type of `main()` to make this compile.
fn main() -> Result<(), ParseIntError> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Ok(())
}
// Don't change anything below this line.
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
match value {
x if x < 0 => Err(CreationError::Negative),
x if x == 0 => Err(CreationError::Zero),
x => Ok(PositiveNonzeroInteger(x as u64))
}
}
}
// This is required so that `CreationError` can implement `error::Error`.
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
CreationError::Negative => "number is negative",
CreationError::Zero => "number is zero",
};
f.write_str(description)
}
}
impl error::Error for CreationError {}

View file

@ -0,0 +1,95 @@
// errors6.rs
// 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
// error content, instead of printing it out or propagating it further. Here,
// we define a custom error type to make it possible for callers to decide
// what to do next when our function returns an error.
// Make these tests pass! Execute `rustlings hint errors6` for hints :)
// I AM NOT DONE
use std::num::ParseIntError;
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError)
}
impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// TODO: add another error conversion function here.
}
fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
let x: i64 = s.parse().unwrap();
PositiveNonzeroInteger::new(x)
.map_err(ParsePosNonzeroError::from_creation)
}
// Don't change anything below this line.
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
match value {
x if x < 0 => Err(CreationError::Negative),
x if x == 0 => Err(CreationError::Zero),
x => Ok(PositiveNonzeroInteger(x as u64))
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_error() {
// We can't construct a ParseIntError, so we have to pattern match.
assert!(matches!(
parse_pos_nonzero("not a number"),
Err(ParsePosNonzeroError::ParseInt(_))
));
}
#[test]
fn test_negative() {
assert_eq!(
parse_pos_nonzero("-555"),
Err(ParsePosNonzeroError::Creation(CreationError::Negative))
);
}
#[test]
fn test_zero() {
assert_eq!(
parse_pos_nonzero("0"),
Err(ParsePosNonzeroError::Creation(CreationError::Zero))
);
}
#[test]
fn test_positive() {
let x = PositiveNonzeroInteger::new(42);
assert!(x.is_ok());
assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap()));
}
}

View file

@ -1,115 +0,0 @@
// errorsn.rs
// This is a bigger error exercise than the previous ones!
// You can do it! :)
//
// Edit the `read_and_validate` function ONLY. Don't create any Errors
// that do not already exist.
//
// So many things could go wrong!
//
// - Reading from stdin could produce an io::Error
// - Parsing the input could produce a num::ParseIntError
// - Validating the input could produce a CreationError (defined below)
//
// How can we lump these errors into one general error? That is, what
// type goes where the question marks are, and how do we return
// that type from the body of read_and_validate?
//
// Execute `rustlings hint errorsn` for hints :)
use std::error;
use std::fmt;
use std::io;
// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> {
let mut line = String::new();
b.read_line(&mut line)?;
let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num)?;
Ok(answer)
}
//
// Nothing below this needs to be modified
//
// This is a test helper function that turns a &str into a BufReader.
fn test_with_str(s: &str) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> {
let mut b = io::BufReader::new(s.as_bytes());
read_and_validate(&mut b)
}
#[test]
fn test_success() {
let x = test_with_str("42\n");
assert_eq!(PositiveNonzeroInteger(42), x.unwrap());
}
#[test]
fn test_not_num() {
let x = test_with_str("eleven billion\n");
assert!(x.is_err());
}
#[test]
fn test_non_positive() {
let x = test_with_str("-40\n");
assert!(x.is_err());
}
#[test]
fn test_ioerror() {
struct Broken;
impl io::Read for Broken {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "uh-oh!"))
}
}
let mut b = io::BufReader::new(Broken);
assert!(read_and_validate(&mut b).is_err());
assert_eq!("uh-oh!", read_and_validate(&mut b).unwrap_err().to_string());
}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
if value == 0 {
Err(CreationError::Zero)
} else if value < 0 {
Err(CreationError::Negative)
} else {
Ok(PositiveNonzeroInteger(value as u64))
}
}
}
#[test]
fn test_positive_nonzero_integer_creation() {
assert!(PositiveNonzeroInteger::new(10).is_ok());
assert_eq!(
Err(CreationError::Negative),
PositiveNonzeroInteger::new(-10)
);
assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
CreationError::Negative => "Number is negative",
CreationError::Zero => "Number is zero",
};
f.write_str(description)
}
}
impl error::Error for CreationError {}

View file

@ -1,9 +1,8 @@
// functions1.rs // functions1.rs
// Make me compile! Execute `rustlings hint functions1` for hints :) // Make me compile! Execute `rustlings hint functions1` for hints :)
// I AM NOT DONE
fn main() { fn main() {
call_me(); call_me();
} }
fn call_me() {
println!("Called!");
}

View file

@ -1,11 +1,13 @@
// functions2.rs // functions2.rs
// Make me compile! Execute `rustlings hint functions2` for hints :) // Make me compile! Execute `rustlings hint functions2` for hints :)
// I AM NOT DONE
fn main() { fn main() {
call_me(7); call_me(3);
} }
fn call_me(num:i32) { fn call_me(num:) {
for i in 0..num { for i in 0..num {
println!("Ring! Call number {}", i + 1); println!("Ring! Call number {}", i + 1);
} }

View file

@ -1,8 +1,10 @@
// functions3.rs // functions3.rs
// Make me compile! Execute `rustlings hint functions3` for hints :) // Make me compile! Execute `rustlings hint functions3` for hints :)
// I AM NOT DONE
fn main() { fn main() {
call_me(6); call_me();
} }
fn call_me(num: u32) { fn call_me(num: u32) {

View file

@ -4,12 +4,14 @@
// This store is having a sale where if the price is an even number, you get // This store is having a sale where if the price is an even number, you get
// 10 Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. // 10 Rustbucks off, but if it's an odd number, it's 3 Rustbucks off.
// I AM NOT DONE
fn main() { fn main() {
let original_price = 51; let original_price = 51;
println!("Your sale price is {}", sale_price(original_price)); println!("Your sale price is {}", sale_price(original_price));
} }
fn sale_price(price: i32) -> i32 { fn sale_price(price: i32) -> {
if is_even(price) { if is_even(price) {
price - 10 price - 10
} else { } else {

View file

@ -1,17 +1,13 @@
// functions5.rs // functions5.rs
// Make me compile! Execute `rustlings hint functions5` for hints :) // Make me compile! Execute `rustlings hint functions5` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let answer = square(3); let answer = square(3);
println!("The answer is {}", answer); println!("The answer is {}", answer);
} }
// without ; the expression is a return statement
// it can be either both num * num or
// return num * num;
// but it cannot be
// return num * num OR num * num;
fn square(num: i32) -> i32 { fn square(num: i32) -> i32 {
num * num num * num;
} }

View file

@ -1,7 +1,11 @@
// This shopping list program isn't compiling! // This shopping list program isn't compiling!
// Use your knowledge of generics to fix it. // Use your knowledge of generics to fix it.
// Execute `rustlings hint generics1` for hints!
// I AM NOT DONE
fn main() { fn main() {
let mut shopping_list: Vec<&str> = Vec::new(); let mut shopping_list: Vec<?> = Vec::new();
shopping_list.push("milk"); shopping_list.push("milk");
} }

View file

@ -1,12 +1,16 @@
// 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.
struct Wrapper<T> { // Execute `rustlings hint generics2` for hints!
value: T,
// I AM NOT DONE
struct Wrapper {
value: u32,
} }
// <T> must be both for impl and Wrapper
impl<T> Wrapper<T> { impl Wrapper {
pub fn new(value: T) -> Self { pub fn new(value: u32) -> Self {
Wrapper { value } Wrapper { value }
} }
} }

View file

@ -10,15 +10,15 @@
// Execute 'rustlings hint generics3' for hints! // Execute 'rustlings hint generics3' for hints!
pub struct ReportCard<T> { // I AM NOT DONE
pub grade: T,
pub struct ReportCard {
pub grade: f32,
pub student_name: String, pub student_name: String,
pub student_age: u8, pub student_age: u8,
} }
// <T> must implement std::fmt::Display or no format!() macro impl ReportCard {
// for you
impl<T: std::fmt::Display> ReportCard<T> {
pub fn print(&self) -> String { pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}", format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade) &self.student_name, &self.student_age, &self.grade)
@ -46,7 +46,7 @@ mod tests {
fn generate_alphabetic_report_card() { fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise. // TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard { let report_card = ReportCard {
grade: "A+".to_string(), grade: 2.1,
student_name: "Gary Plotter".to_string(), student_name: "Gary Plotter".to_string(),
student_age: 11, student_age: 11,
}; };

View file

@ -1,16 +1,13 @@
// if1.rs // if1.rs
// I AM NOT DONE
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number! // Complete this function to return the bigger number!
// Do not use: // Do not use:
// - another function call // - another function call
// - additional variables // - additional variables
// Execute `rustlings hint if1` for hints // Execute `rustlings hint if1` for hints
pub fn bigger(a: i32, b: i32) -> i32 {
if a > b {
a
} else {
b
}
} }
// Don't mind this for now :) // Don't mind this for now :)

View file

@ -4,14 +4,13 @@
// 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 the command `rustlings hint if2` if you want a hint :) // Execute the command `rustlings hint if2` if you want a hint :)
// I AM NOT DONE
pub fn fizz_if_foo(fizzish: &str) -> &str { pub fn fizz_if_foo(fizzish: &str) -> &str {
if fizzish == "fizz" { if fizzish == "fizz" {
"foo" "foo"
} else if fizzish == "fuzz" {
"bar"
} else { } else {
"baz" 1
} }
} }

View file

@ -1,12 +1,10 @@
// modules1.rs // modules1.rs
// Make me compile! Execute `rustlings hint modules1` for hints :) // Make me compile! Execute `rustlings hint modules1` for hints :)
// `mod` defines a module which can contain functions, structs etc. // I AM NOT DONE
// by default, its `fn`s only limited within itself, creating "closed
// ecosystem". you can make them public with `pub`
mod sausage_factory { mod sausage_factory {
pub fn make_sausage() { fn make_sausage() {
println!("sausage!"); println!("sausage!");
} }
} }

View file

@ -1,9 +1,11 @@
// modules2.rs // modules2.rs
// Make me compile! Execute `rustlings hint modules2` for hints :) // Make me compile! Execute `rustlings hint modules2` for hints :)
// I AM NOT DONE
mod delicious_snacks { mod delicious_snacks {
pub use self::fruits::PEAR as fruit; use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie; use self::veggies::CUCUMBER as veggie;
mod fruits { mod fruits {
pub const PEAR: &'static str = "Pear"; pub const PEAR: &'static str = "Pear";

View file

@ -1,11 +1,12 @@
// move_semantics1.rs // move_semantics1.rs
// Make me compile! Execute `rustlings hint move_semantics1` for hints :) // Make me compile! Execute `rustlings hint move_semantics1` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let vec0 = Vec::new(); let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0); let vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

View file

@ -2,10 +2,12 @@
// Make me compile without changing line 13! // Make me compile without changing line 13!
// Execute `rustlings hint move_semantics2` for hints :) // Execute `rustlings hint move_semantics2` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let vec0 = Vec::new(); let vec0 = Vec::new();
let mut vec1 = fill_vec(&vec0); let mut vec1 = fill_vec(vec0);
// Do not change the following line! // Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
@ -15,8 +17,8 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
} }
fn fill_vec(vec: &[i32]) -> Vec<i32> { fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec.to_vec(); let mut vec = vec;
vec.push(22); vec.push(22);
vec.push(44); vec.push(44);

View file

@ -3,10 +3,12 @@
// (no lines with multiple semicolons necessary!) // (no lines with multiple semicolons necessary!)
// Execute `rustlings hint move_semantics3` for hints :) // Execute `rustlings hint move_semantics3` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let vec0 = Vec::new(); let vec0 = Vec::new();
let mut vec1 = fill_vec(&vec0); let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
@ -15,8 +17,7 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
} }
fn fill_vec(vec: &[i32]) -> Vec<i32> { fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec.to_vec();
vec.push(22); vec.push(22);
vec.push(44); vec.push(44);
vec.push(66); vec.push(66);

View file

@ -4,11 +4,12 @@
// freshly created vector from fill_vec to its caller. // freshly created vector from fill_vec to its caller.
// Execute `rustlings hint move_semantics4` for hints! // Execute `rustlings hint move_semantics4` for hints!
// I AM NOT DONE
fn main() { fn main() {
// let vec0 = Vec::new(); let vec0 = Vec::new();
let mut vec1 = fill_vec(); let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
@ -19,7 +20,7 @@ fn main() {
// `fill_vec()` no longer takes `vec: Vec<i32>` as argument // `fill_vec()` no longer takes `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> { fn fill_vec() -> Vec<i32> {
let mut vec = Vec::new(); let mut vec = vec;
vec.push(22); vec.push(22);
vec.push(44); vec.push(44);

View file

@ -0,0 +1,15 @@
// move_semantics5.rs
// Make me compile without adding, removing, or changing any of the
// lines in `main()`.
// Execute `rustlings hint move_semantics5` for hints :)
// I AM NOT DONE
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut *y;
*y += 100;
*z += 1000;
assert_eq!(x, 1200);
}

View file

@ -9,16 +9,15 @@ fn print_number(maybe_number: Option<u16>) {
} }
fn main() { fn main() {
// rustc suggested solutions print_number(13);
print_number(Some(13)); print_number(99);
print_number(Some(99));
let numbers: [Option<u16>; 5]; let mut numbers: [Option<u16>; 5];
for iter in 0..5 { for iter in 0..5 {
let number_to_add: u16 = { let number_to_add: u16 = {
((iter * 1235) + 2) / (4 * 16) ((iter * 1235) + 2) / (4 * 16)
}; };
numbers[iter as usize] = Some(number_to_add); numbers[iter as usize] = number_to_add;
} }
} }

View file

@ -0,0 +1,19 @@
// option3.rs
// Make me compile! Execute `rustlings hint option3` for hints
// I AM NOT DONE
struct Point {
x: i32,
y: i32,
}
fn main() {
let y: Option<Point> = Some(Point { x: 100, y: 200 });
match y {
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => println!("no match"),
}
y; // Fix without deleting this line.
}

View file

@ -2,6 +2,8 @@
// Fill in the rest of the line that has code missing! // Fill in the rest of the line that has code missing!
// No hints, there's no tricks, just get used to typing these :) // No hints, there's no tricks, just get used to typing these :)
// I AM NOT DONE
fn main() { fn main() {
// Booleans (`bool`) // Booleans (`bool`)
@ -10,7 +12,7 @@ fn main() {
println!("Good morning!"); println!("Good morning!");
} }
let is_evening = true; // Finish the rest of this line like the example! Or make it be false! let // Finish the rest of this line like the example! Or make it be false!
if is_evening { if is_evening {
println!("Good evening!"); println!("Good evening!");
} }

View file

@ -2,6 +2,8 @@
// Fill in the rest of the line that has code missing! // Fill in the rest of the line that has code missing!
// No hints, there's no tricks, just get used to typing these :) // No hints, there's no tricks, just get used to typing these :)
// I AM NOT DONE
fn main() { fn main() {
// Characters (`char`) // Characters (`char`)
@ -14,7 +16,7 @@ fn main() {
println!("Neither alphabetic nor numeric!"); println!("Neither alphabetic nor numeric!");
} }
let your_character = 'D'; // Finish this line like the example! What's your favorite character? let // Finish this line like the example! What's your favorite character?
// Try a letter, try a number, try a special character, try a character // Try a letter, try a number, try a special character, try a character
// from a different language than your own, try an emoji! // from a different language than your own, try an emoji!
if your_character.is_alphabetic() { if your_character.is_alphabetic() {

View file

@ -2,9 +2,10 @@
// 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` for hints! // Execute `rustlings hint primitive_types3` for hints!
// I AM NOT DONE
fn main() { fn main() {
let a: [i32; 300] = [0; 300]; let a = ???
if a.len() >= 100 { if a.len() >= 100 {
println!("Wow, that's a big array!"); println!("Wow, that's a big array!");

View file

@ -2,11 +2,13 @@
// 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` for hints!! // Execute `rustlings hint primitive_types4` for hints!!
// I AM NOT DONE
#[test] #[test]
fn slice_out_of_array() { fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5]; let a = [1, 2, 3, 4, 5];
let nice_slice = &a[1..4]; let nice_slice = ???
assert_eq!([2, 3, 4], nice_slice) assert_eq!([2, 3, 4], nice_slice)
} }

View file

@ -2,9 +2,11 @@
// 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` for hints! // Execute `rustlings hint primitive_types5` for hints!
// I AM NOT DONE
fn main() { fn main() {
let cat = ("Furry McFurson", 3.5); let cat = ("Furry McFurson", 3.5);
let (name, age) = cat; let /* your pattern here */ = cat;
println!("{} is {} years old.", name, age); println!("{} is {} years old.", name, age);
} }

View file

@ -2,11 +2,14 @@
// Use a tuple index to access the second element of `numbers`. // 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. // You can put the expression for the second element where ??? is so that the test passes.
// Execute `rustlings hint primitive_types6` for hints! // Execute `rustlings hint primitive_types6` for hints!
// I AM NOT DONE
#[test] #[test]
fn indexing_tuple() { fn indexing_tuple() {
let numbers = (1, 2, 3); let numbers = (1, 2, 3);
// Replace below ??? with the tuple indexing syntax. // Replace below ??? with the tuple indexing syntax.
let second = numbers.1; let second = ???;
assert_eq!(2, second, assert_eq!(2, second,
"This is not the 2nd number in the tuple!") "This is not the 2nd number in the tuple!")

View file

@ -7,23 +7,19 @@
// more than 40 at once, each apple only costs 1! Write a function that calculates // more than 40 at once, each apple only costs 1! Write a function that calculates
// the price of an order of apples given the order amount. No hints this time! // the price of an order of apples given the order amount. No hints this time!
// I AM NOT DONE
// Put your function here! // Put your function here!
// fn ..... { // fn ..... {
fn calculate_apple_price(amount: i32) -> i32 {
if amount > 40 {
1 * amount
} else {
2 * amount
}
}
// Don't modify this function! // Don't modify this function!
#[test] #[test]
fn verify_test() { fn verify_test() {
let price1 = calculate_apple_price(35); let price1 = calculate_apple_price(35);
let price2 = calculate_apple_price(65); let price2 = calculate_apple_price(40);
let price3 = calculate_apple_price(65);
assert_eq!(70, price1); assert_eq!(70, price1);
assert_eq!(65, price2); assert_eq!(80, price2);
assert_eq!(65, price3);
} }

View file

@ -7,6 +7,8 @@
// 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!
// I AM NOT DONE
fn string_slice(arg: &str) { fn string_slice(arg: &str) {
println!("{}", arg); println!("{}", arg);
} }
@ -15,14 +17,14 @@ fn string(arg: String) {
} }
fn main() { fn main() {
string_slice("blue"); ???("blue");
string("red".to_string()); ???("red".to_string());
string(String::from("hi")); ???(String::from("hi"));
string("rust is fun!".to_owned()); ???("rust is fun!".to_owned());
string("nice weather".into()); ???("nice weather".into());
string(format!("Interpolation {}", "Station")); ???(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]); ???(&String::from("abc")[0..1]);
string_slice(" hello there ".trim()); ???(" hello there ".trim());
string("Happy Monday!".to_string().replace("Mon", "Tues")); ???("Happy Monday!".to_string().replace("Mon", "Tues"));
string("mY sHiFt KeY iS sTiCkY".to_lowercase()); ???("mY sHiFt KeY iS sTiCkY".to_lowercase());
} }

View file

@ -7,8 +7,7 @@
// imperative style for loops. Recreate this counting functionality using // imperative style for loops. Recreate this counting functionality using
// iterators. Only the two iterator methods (count_iterator and // iterators. Only the two iterator methods (count_iterator and
// count_collection_iterator) need to be modified. // count_collection_iterator) need to be modified.
// Execute `rustlings hint // Execute `rustlings hint iterators5` for hints.
// iterators5` for hints.
// //
// Make the code compile and the tests pass. // Make the code compile and the tests pass.
@ -16,7 +15,7 @@
use std::collections::HashMap; use std::collections::HashMap;
#[derive(PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
enum Progress { enum Progress {
None, None,
Some, Some,

View file

@ -2,13 +2,13 @@
// Make me compile without changing the function signature! // Make me compile without changing the function signature!
// Execute `rustlings hint strings1` for hints ;) // Execute `rustlings hint strings1` for hints ;)
// I AM NOT DONE
fn main() { fn main() {
let answer = current_favorite_color(); let answer = current_favorite_color();
println!("My current favorite color is {}", answer); println!("My current favorite color is {}", answer);
} }
fn current_favorite_color() -> String { fn current_favorite_color() -> String {
// .to_string uses fmt trait "blue"
// .to_owned works too
"blue".to_owned()
} }

View file

@ -2,6 +2,8 @@
// Make me compile without changing the function signature! // Make me compile without changing the function signature!
// Execute `rustlings hint strings2` for hints :) // Execute `rustlings hint strings2` for hints :)
// I AM NOT DONE
fn main() { fn main() {
let word = String::from("green"); // Try not changing this line :) let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(word) { if is_a_color_word(word) {
@ -11,6 +13,6 @@ fn main() {
} }
} }
fn is_a_color_word(attempt: String) -> bool { fn is_a_color_word(attempt: &str) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red" attempt == "green" || attempt == "blue" || attempt == "red"
} }

View file

@ -1,12 +1,13 @@
// structs1.rs // structs1.rs
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// I AM NOT DONE
struct ColorClassicStruct { struct ColorClassicStruct {
name: String, // TODO: Something goes here
hex: String
} }
struct ColorTupleStruct(String, String); struct ColorTupleStruct(/* TODO: Something goes here */);
#[derive(Debug)] #[derive(Debug)]
struct UnitStruct; struct UnitStruct;
@ -18,10 +19,8 @@ mod tests {
#[test] #[test]
fn classic_c_structs() { fn classic_c_structs() {
// TODO: Instantiate a classic c struct! // TODO: Instantiate a classic c struct!
let green = ColorClassicStruct { // let green =
name: String::from("green"),
hex: String::from("#00FF00")
};
assert_eq!(green.name, "green"); assert_eq!(green.name, "green");
assert_eq!(green.hex, "#00FF00"); assert_eq!(green.hex, "#00FF00");
} }
@ -29,7 +28,7 @@ mod tests {
#[test] #[test]
fn tuple_structs() { fn tuple_structs() {
// TODO: Instantiate a tuple struct! // TODO: Instantiate a tuple struct!
let green = ColorTupleStruct("green".to_string(),"#00FF00".to_string()); // let green =
assert_eq!(green.0, "green"); assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00"); assert_eq!(green.1, "#00FF00");
@ -38,7 +37,7 @@ mod tests {
#[test] #[test]
fn unit_structs() { fn unit_structs() {
// TODO: Instantiate a unit struct! // TODO: Instantiate a unit struct!
let unit_struct = UnitStruct; // let unit_struct =
let message = format!("{:?}s are fun!", unit_struct); let message = format!("{:?}s are fun!", unit_struct);
assert_eq!(message, "UnitStructs are fun!"); assert_eq!(message, "UnitStructs are fun!");

View file

@ -1,6 +1,8 @@
// structs2.rs // structs2.rs
// Address all the TODOs to make the tests pass! // Address all the TODOs to make the tests pass!
// I AM NOT DONE
#[derive(Debug)] #[derive(Debug)]
struct Order { struct Order {
name: String, name: String,
@ -32,15 +34,7 @@ mod tests {
fn your_order() { fn your_order() {
let order_template = create_order_template(); let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above! // TODO: Create your own order using the update syntax and template above!
let your_order = Order { // let your_order =
name: String::from("Hacker in Rust"),
year: 2019,
made_by_phone: false,
made_by_mobile: false,
made_by_email: true,
item_number: 123,
count: 1,
};
assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year); assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone); assert_eq!(your_order.made_by_phone, order_template.made_by_phone);

View file

@ -4,6 +4,7 @@
// Make the code compile and the tests pass! // Make the code compile and the tests pass!
// If you have issues execute `rustlings hint structs3` // If you have issues execute `rustlings hint structs3`
// I AM NOT DONE
#[derive(Debug)] #[derive(Debug)]
struct Package { struct Package {
@ -15,7 +16,7 @@ struct Package {
impl Package { impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package { fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
if weight_in_grams <= 0 { if weight_in_grams <= 0 {
panic!("Weight is in negative value."); // Something goes here...
} else { } else {
return Package { return Package {
sender_country, sender_country,
@ -25,20 +26,12 @@ impl Package {
} }
} }
fn is_international(&self) -> bool { fn is_international(&self) -> ??? {
if self.sender_country != self.recipient_country { // Something goes here...
true
} else {
false
}
} }
fn get_fees(&self, cents_per_gram: i32) -> i32 { fn get_fees(&self, cents_per_gram: i32) -> ??? {
if cents_per_gram <= 0 { // Something goes here...
panic!("We don't pay people, do we?");
} else {
cents_per_gram * self.weight_in_grams
}
} }
} }
@ -80,7 +73,7 @@ mod tests {
let sender_country = String::from("Spain"); let sender_country = String::from("Spain");
let recipient_country = String::from("Spain"); let recipient_country = String::from("Spain");
let cents_per_gram = 3; let cents_per_gram = ???;
let package = Package::new(sender_country, recipient_country, 1500); let package = Package::new(sender_country, recipient_country, 1500);

View file

@ -6,7 +6,9 @@
// even after you already figured it out. If you got everything working and // even 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. // feel ready for the next exercise, remove the `I AM NOT DONE` comment below.
// I AM NOT DONE
fn main() { fn main() {
let x = 5; x = 5;
println!("x has the value {}", x); println!("x has the value {}", x);
} }

View file

@ -1,9 +1,10 @@
// variables2.rs // variables2.rs
// Make me compile! Execute the command `rustlings hint variables2` if you want a hint :) // Make me compile! Execute the command `rustlings hint variables2` if you want a hint :)
// I AM NOT DONE
fn main() { fn main() {
let x = 10; let x;
if x == 10 { if x == 10 {
println!("Ten!"); println!("Ten!");
} else { } else {

View file

@ -1,8 +1,10 @@
// variables3.rs // variables3.rs
// Make me compile! Execute the command `rustlings hint variables3` if you want a hint :) // Make me compile! Execute the command `rustlings hint variables3` if you want a hint :)
// I AM NOT DONE
fn main() { fn main() {
let mut x = 3; let x = 3;
println!("Number {}", x); println!("Number {}", x);
x = 5; // don't change this line x = 5; // don't change this line
println!("Number {}", x); println!("Number {}", x);

View file

@ -1,8 +1,9 @@
// variables4.rs // variables4.rs
// Make me compile! Execute the command `rustlings hint variables4` if you want a hint :) // Make me compile! Execute the command `rustlings hint variables4` if you want a hint :)
// I AM NOT DONE
fn main() { fn main() {
let mut x: i32; let x: i32;
x = 512;
println!("Number {}", x); println!("Number {}", x);
} }

View file

@ -1,9 +1,11 @@
// variables5.rs // variables5.rs
// Make me compile! Execute the command `rustlings hint variables5` if you want a hint :) // Make me compile! Execute the command `rustlings hint variables5` if you want a hint :)
// I AM NOT DONE
fn main() { fn main() {
let number = "T-H-R-E-E"; let number = "T-H-R-E-E"; // don't change this line
println!("Spell a Number : {}", number); println!("Spell a Number : {}", number);
let number = 3; number = 3;
println!("Number plus two is : {}", number + 2); println!("Number plus two is : {}", number + 2);
} }

View file

@ -1,9 +1,9 @@
// variables6.rs // variables6.rs
// Make me compile! Execute the command `rustlings hint variables6` if you want a hint :) // Make me compile! Execute the command `rustlings hint variables6` if you want a hint :)
// consts have to have strict data type definition // I AM NOT DONE
// otherwise they won't work
const NUMBER: i32 = 3; const NUMBER = 3;
fn main() { fn main() {
println!("Number {}", NUMBER); println!("Number {}", NUMBER);
} }

View file

@ -772,10 +772,7 @@ The division_results variable needs to be collected into a collection type.
The result_with_list function needs to return a single Result where the success The result_with_list function needs to return a single Result where the success
case is a vector of integers and the failure case is a DivisionError. case is a vector of integers and the failure case is a DivisionError.
The list_of_results function needs to return a vector of results. The list_of_results function needs to return a vector of results."""
See https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect for how
the `FromIterator` trait is used in `collect()`."""
[[exercises]] [[exercises]]
name = "iterators4" name = "iterators4"
@ -902,15 +899,7 @@ name = "clippy1"
path = "exercises/clippy/clippy1.rs" path = "exercises/clippy/clippy1.rs"
mode = "clippy" mode = "clippy"
hint = """ hint = """
Not every floating point value can be represented exactly in binary values in Floating point calculations are usually imprecise, so asking if two values are exactly equal is asking for trouble"""
memory. Take a look at the description of
https://doc.rust-lang.org/stable/std/primitive.f32.html
When using the binary compare operators with floating points you won't compare
the floating point values but the binary representation in memory. This is
usually not what you would like to do.
See the suggestions of the clippy warning in compile output and use the
machine epsilon value...
https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.EPSILON"""
[[exercises]] [[exercises]]
name = "clippy2" name = "clippy2"

View file

@ -286,16 +286,6 @@ fn spawn_watch_shell(failed_exercise_hint: &Arc<Mutex<Option<String>>>) {
} }
fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise { fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise {
if name.eq("next") {
exercises
.iter()
.find(|e| !e.looks_done())
.unwrap_or_else(|| {
println!("🎉 Congratulations! You have done all the exercises!");
println!("🔚 There are no more exercises to do next!");
std::process::exit(1)
})
} else {
exercises exercises
.iter() .iter()
.find(|e| e.name == name) .find(|e| e.name == name)
@ -303,7 +293,6 @@ fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise {
println!("No exercise found for '{}'!", name); println!("No exercise found for '{}'!", name);
std::process::exit(1) std::process::exit(1)
}) })
}
} }
fn watch(exercises: &[Exercise], verbose: bool) -> notify::Result<()> { fn watch(exercises: &[Exercise], verbose: bool) -> notify::Result<()> {