Browse Source

Exercism: Health Statistics

master
Julio Biason 3 years ago
parent
commit
d11f843f9e
  1. 17
      rust/health-statistics/.exercism/config.json
  2. 1
      rust/health-statistics/.exercism/metadata.json
  3. 7
      rust/health-statistics/Cargo.lock
  4. 5
      rust/health-statistics/Cargo.toml
  5. 85
      rust/health-statistics/HELP.md
  6. 31
      rust/health-statistics/HINTS.md
  7. 91
      rust/health-statistics/README.md
  8. 35
      rust/health-statistics/src/lib.rs
  9. 39
      rust/health-statistics/tests/health-statistics.rs

17
rust/health-statistics/.exercism/config.json

@ -0,0 +1,17 @@
{
"blurb": "Learn structs to store statistics for a health-monitoring system.",
"authors": [
"seanchen1991"
],
"files": {
"solution": [
"src/lib.rs"
],
"test": [
"tests/health-statistics.rs"
],
"exemplar": [
".meta/exemplar.rs"
]
}
}

1
rust/health-statistics/.exercism/metadata.json

@ -0,0 +1 @@
{"track":"rust","exercise":"health-statistics","id":"6c35f450897f44b2a60c5f8e8d6c993b","url":"https://exercism.org/tracks/rust/exercises/health-statistics","handle":"JBiason","is_requester":true,"auto_approve":false}

7
rust/health-statistics/Cargo.lock generated

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "health_statistics"
version = "0.1.0"

5
rust/health-statistics/Cargo.toml

@ -0,0 +1,5 @@
[package]
name = "health_statistics"
version = "0.1.0"
edition = "2018"

85
rust/health-statistics/HELP.md

@ -0,0 +1,85 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ cargo test
```
All but the first test have been ignored. After you get the first test to
pass, open the tests source file which is located in the `tests` directory
and remove the `#[ignore]` flag from the next test and get the tests to pass
again. Each separate test is a function with `#[test]` flag above it.
Continue, until you pass every test.
If you wish to run _only ignored_ tests without editing the tests source file, use:
```bash
$ cargo test -- --ignored
```
If you are using Rust 1.51 or later, you can run _all_ tests with
```bash
$ cargo test -- --include-ignored
```
To run a specific test, for example `some_test`, you can use:
```bash
$ cargo test some_test
```
If the specific test is ignored, use:
```bash
$ cargo test some_test -- --ignored
```
To learn more about Rust tests refer to the online [test documentation][rust-tests].
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
## Submitting your solution
You can submit your solution using the `exercism submit src/lib.rs` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## Submitting the solution
Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer.
## Feedback, Issues, Pull Requests
The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!
If you want to know more about Exercism, take a look at the [contribution guide].
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
[help-page]: https://exercism.io/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.io/docs/community/contributors

31
rust/health-statistics/HINTS.md

@ -0,0 +1,31 @@
# Hints
## General
## 1. Implement the `new()` method
- The `new()` method receives the arguments we want to instantiate a `User` instance with. It should return an instance of `User` with the specified name, age, and weight.
- See [here](https://doc.rust-lang.org/book/ch05-01-defining-structs.html) for additional examples on defining and instantiating structs.
## 2. Implement the getter methods
- The `name()`, `age()`, and `weight()` methods are getters. In other words, they are responsible for returning the corresponding field from a struct instance.
- Notice that the `name` method returns a `&str` when the `name` field on the `User` struct is a `String`. How can we get `&str` and `String` to play nice with each other?
- There's no need to use a `return` statement in Rust unless you expressly want a function or method to return early. Otherwise, it's more idiomatic to utilize an _implicit_ return by omitting the semicolon for the result we want a function or method to return. It's not _wrong_ to use an explicit return, but it's cleaner to take advantage of implicit returns where possible.
```rust
fn foo() -> i32 {
1
}
```
- See [here](https://doc.rust-lang.org/book/ch05-03-method-syntax.html) for some more examples of defining methods on structs.
## 3. Implement the setter methods
- The `set_age()` and `set_weight()` methods are setters, responsible for updating the corresponding field on a struct instance with the input argument.
- As the signatures of these methods specify, the setter methods shouldn't return anything.

91
rust/health-statistics/README.md

@ -0,0 +1,91 @@
# Health Statistics
Welcome to Health Statistics on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
It is often useful to group a collection of items together, and handle those groups as units. In Rust, we call such a group a struct, and each item one of the struct's fields. A struct defines the general set of fields available, but a particular example of a struct is called an instance.
Furthermore, structs can have methods defined on them, which have access to the fields. The struct itself in that case is referred to as `self`. When a method uses `&mut self`, the fields can be changed, or mutated. When a method uses `&self`, the fields cannot be changed: they are immutable. Controlling mutability helps the borrow-checker ensure that entire classes of concurrency bug just don't happen in Rust.
In this exercise, you'll be implementing two kinds of methods on a struct. The first are generally known as getters: they expose the struct's fields to the world, without letting anyone else mutate that value. In Rust, these methods idiomatically share the name of the field they expose, i.e., if we have a getter method that fetches a struct field called `name`, the method would simply be called `name()`.
You'll also be implementing methods of another type, generally known as setters. These change the value of the field. Setters aren't very common in Rust--if a field can be freely modified, it is more common to just make it public--but they're useful if updating the field should have side effects, or for access control: a setter marked as `pub(crate)` allows other modules within the same crate to update a private field, which can't be affected by the outside world.
Structs come in three flavors: structs with named fields, tuple structs, and unit structs. For this concept exercise, we'll be exploring the first variant: structs with named fields.
Structs are defined using the `struct` keyword, followed by the capitalized name of the type the struct is describing:
```rust
struct Item {}
```
Additional types are then brought into the struct body as _fields_ of the struct, each with their own type:
```rust
struct Item {
name: String,
weight: f32,
worth: u32,
}
```
Lastly, methods can be defined on structs inside of an `impl` block:
```rust
impl Item {
// initializes and returns a new instance of our Item struct
fn new() -> Self {
unimplemented!()
}
}
```
With that brief introduction to the syntax of structs out of the way, go ahead and take a look at the [instructions](instructions.md) for this exercise!
## Instructions
You're working on implementing a health-monitoring system. As part of that, you need to keep track of users' health statistics.
You'll start with some stubbed functions in an `impl` block as well as the following struct definition:
```rust
pub struct User {
name: String,
age: u32,
weight: f32,
}
```
Your goal is to implement the stubbed out methods on the `User` `struct` defined in the `impl` block.
For example, the `new` method should return an instance of the `User` struct with the specified name, age, and weight values.
```rust
let mut bob = User::new(String::from("Bob"), 32, 155.2);
// Returns: a User with name "Bob", age 32, and weight 155.2
```
The `weight` method should return the weight of the `User`.
```rust
bob.weight();
// Returns: 155.2
```
The `set_age` method should set the age of the `User`.
```rust
bob.set_age(33);
// Updates Bob's age to 33; happy birthday Bob!
```
Have fun!
## Source
### Created by
- @seanchen1991

35
rust/health-statistics/src/lib.rs

@ -0,0 +1,35 @@
// This stub file contains items which aren't used yet; feel free to remove this module attribute
// to enable stricter warnings.
#![allow(unused)]
pub struct User {
name: String,
age: u32,
weight: f32,
}
impl User {
pub fn new(name: String, age: u32, weight: f32) -> Self {
Self { name, age, weight }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn age(&self) -> u32 {
self.age
}
pub fn weight(&self) -> f32 {
self.weight
}
pub fn set_age(&mut self, new_age: u32) {
self.age = new_age;
}
pub fn set_weight(&mut self, new_weight: f32) {
self.weight = new_weight
}
}

39
rust/health-statistics/tests/health-statistics.rs

@ -0,0 +1,39 @@
use health_statistics::*;
const NAME: &str = "Ebenezer";
const AGE: u32 = 89;
const WEIGHT: f32 = 131.6;
#[test]
fn test_name() {
let user = User::new(NAME.into(), AGE, WEIGHT);
assert_eq!(user.name(), NAME);
}
#[test]
fn test_age() {
let user = User::new(NAME.into(), AGE, WEIGHT);
assert_eq!(user.age(), AGE);
}
#[test]
fn test_weight() {
let user = User::new(NAME.into(), AGE, WEIGHT);
assert!((user.weight() - WEIGHT).abs() < f32::EPSILON);
}
#[test]
fn test_set_age() {
let new_age: u32 = 90;
let mut user = User::new(NAME.into(), AGE, WEIGHT);
user.set_age(new_age);
assert_eq!(user.age(), new_age);
}
#[test]
fn test_set_weight() {
let new_weight: f32 = 129.4;
let mut user = User::new(NAME.into(), AGE, WEIGHT);
user.set_weight(new_weight);
assert!((user.weight() - new_weight).abs() < f32::EPSILON);
}
Loading…
Cancel
Save