Guest User

rustlings/quizzes/quiz2.rs

a guest
Sep 2nd, 2025
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.14 KB | Source Code | 0 0
  1. // This is a quiz for the following sections:
  2. // - Strings
  3. // - Vecs
  4. // - Move semantics
  5. // - Modules
  6. // - Enums
  7. //
  8. // Let's build a little machine in the form of a function. As input, we're going
  9. // to give a list of strings and commands. These commands determine what action
  10. // is going to be applied to the string. It can either be:
  11. // - Uppercase the string
  12. // - Trim the string
  13. // - Append "bar" to the string a specified amount of times
  14. //
  15. // The exact form of this will be:
  16. // - The input is going to be a Vector of 2-length tuples,
  17. //   the first element is the string, the second one is the command.
  18. // - The output element is going to be a vector of strings.
  19.  
  20. enum Command {
  21.     Uppercase,
  22.     Trim,
  23.     Append(usize),
  24. }
  25.  
  26. mod my_module {
  27.     use super::Command;
  28.  
  29.     // TODO: Complete the function as described above.
  30.     // pub fn transformer(input: ???) -> ??? { ??? }
  31.     pub fn transformer(input: Vec<(String, Command)>)->Vec<String>{
  32.         let mut output = Vec::new();
  33.         for (s, c) in input.iter() {
  34.             match c {
  35.                 Command::Uppercase => {output.push(s.to_uppercase());}
  36.                 Command::Trim => {output.push(s.trim().to_string());}
  37.                 Command::Append(x) => {output.push(s.to_owned()+&"bar".repeat(*x));}
  38.             }
  39.         }
  40.         output
  41.  
  42.     }
  43. }
  44.  
  45. fn main() {
  46.     // You can optionally experiment here.
  47. }
  48.  
  49. #[cfg(test)]
  50. mod tests {
  51.     // TODO: What do we need to import to have `transformer` in scope?
  52.     // use ???;
  53.     use super::Command;
  54.     use super::my_module::transformer;
  55.  
  56.     #[test]
  57.     fn it_works() {
  58.         let input = vec![
  59.             ("hello".to_string(), Command::Uppercase),
  60.             (" all roads lead to rome! ".to_string(), Command::Trim),
  61.             ("foo".to_string(), Command::Append(1)),
  62.             ("bar".to_string(), Command::Append(5)),
  63.         ];
  64.         let output = transformer(input);
  65.  
  66.         assert_eq!(
  67.             output,
  68.             [
  69.                 "HELLO",
  70.                 "all roads lead to rome!",
  71.                 "foobar",
  72.                 "barbarbarbarbarbar",
  73.             ]
  74.         );
  75.     }
  76. }
  77.  
Add Comment
Please, Sign In to add comment