mirror of https://github.com/01-edu/public.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.7 KiB
65 lines
1.7 KiB
2 years ago
|
## check_user_name
|
||
|
|
||
|
### Instructions
|
||
|
|
||
|
Sometimes it is more desirable to catch the failure of some parts of a program instead of just calling panic.
|
||
|
|
||
|
For this exercise you will have to create a tool that manages users' access levels.
|
||
|
|
||
2 years ago
|
You will have to create an `AccessLevel` enum which could be `Guest`, `Normal`, `Admin`.
|
||
2 years ago
|
|
||
|
You will also have to create a `User` struct which has:
|
||
|
|
||
2 years ago
|
- Fields:
|
||
2 years ago
|
- `name`: `String`
|
||
|
- `acessLevel`: `enum`
|
||
2 years ago
|
- Associated functions:
|
||
2 years ago
|
- `new`: which initializes the struct.
|
||
2 years ago
|
- `send_name`: which takes only `self` as argument and returns an `Option<&str>` with `None` if the user is a `guest` or the `name` if the `AccessLevel` has any of the other options.
|
||
2 years ago
|
- Other functions:
|
||
2 years ago
|
- `check_user_name`: which takes a `User`, calls `send_name` and returns a `tuple` with `true` and the user `name` if `send_name` returns the name or `false` and `"Error: User is guest"` if not.
|
||
2 years ago
|
|
||
|
### Expected Functions and Data Structures
|
||
|
|
||
|
```rust
|
||
|
pub enum AccessLevel {}
|
||
|
|
||
|
pub struct User {}
|
||
|
|
||
|
impl User {
|
||
|
pub fn new(name: String, level: AccessLevel) -> User {}
|
||
|
pub fn send_name(&self) -> Option<&str> {}
|
||
|
}
|
||
|
|
||
|
pub fn check_user_name(user: &User) -> (bool, &str) {}
|
||
|
```
|
||
|
|
||
|
### Usage
|
||
|
|
||
2 years ago
|
Here is a program to test your function:
|
||
2 years ago
|
|
||
|
```rust
|
||
|
use check_user_name::*;
|
||
|
|
||
|
fn main() {
|
||
|
let user0 = User::new("Didier".to_string(), AccessLevel::Admin);
|
||
|
println!("{:?}", check_user_name(&user0));
|
||
|
|
||
2 years ago
|
let user1 = User::new("Mary".to_string(), AccessLevel::Normal);
|
||
|
println!("{:?}", check_user_name(&user1));
|
||
2 years ago
|
|
||
2 years ago
|
let user2 = User::new("John".to_string(), AccessLevel::Guest);
|
||
|
println!("{:?}", check_user_name(&user2));
|
||
2 years ago
|
}
|
||
|
```
|
||
|
|
||
|
And its output:
|
||
|
|
||
|
```console
|
||
|
$ cargo run
|
||
|
(true, "Didier")
|
||
|
(true, "Mary")
|
||
|
(false, "ERROR: User is guest")
|
||
|
$
|
||
|
```
|