1- // quiz2.rs
2- //
3- // This is a quiz for the following sections:
4- // - Strings
5- // - Vecs
6- // - Move semantics
7- // - Modules
8- // - Enums
9- //
10- // Let's build a little machine in the form of a function. As input, we're going
11- // to give a list of strings and commands. These commands determine what action
12- // is going to be applied to the string. It can either be:
13- // - Uppercase the string
14- // - Trim the string
15- // - Append "bar" to the string a specified amount of times
16- // The exact form of this will be:
17- // - The input is going to be a Vector of a 2-length tuple,
18- // the first element is the string, the second one is the command.
19- // - The output element is going to be a Vector of strings.
20- //
21- // No hints this time!
22-
23- // I AM NOT DONE
24-
251pub enum Command {
262 Uppercase ,
273 Trim ,
@@ -31,26 +7,38 @@ pub enum Command {
317mod my_module {
328 use super :: Command ;
339
34- // TODO: Complete the function signature!
35- pub fn transformer ( input : ??? ) -> ??? {
36- // TODO: Complete the output declaration!
37- let mut output: ??? = vec ! [ ] ;
10+ // 补全函数签名:输入是Vec<(String, Command)>,输出是Vec<String>
11+ pub fn transformer ( input : & Vec < ( String , Command ) > ) -> Vec < String > {
12+ // 初始化输出向量,类型为Vec<String>
13+ let mut output: Vec < String > = vec ! [ ] ;
3814 for ( string, command) in input. iter ( ) {
39- // TODO: Complete the function body. You can do it!
15+ // 根据不同命令处理字符串
16+ let result = match command {
17+ Command :: Uppercase => string. to_uppercase ( ) , // 转大写
18+ Command :: Trim => string. trim ( ) . to_string ( ) , // 去除两端空白
19+ Command :: Append ( n) => { // 追加n次"bar"
20+ let mut s = string. clone ( ) ;
21+ for _ in 0 ..* n {
22+ s. push_str ( "bar" ) ;
23+ }
24+ s
25+ }
26+ } ;
27+ output. push ( result) ;
4028 }
4129 output
4230 }
4331}
4432
4533#[ cfg( test) ]
4634mod tests {
47- // TODO: What do we need to import to have `transformer` in scope?
48- use ??? ;
35+ // 导入my_module中的transformer函数
36+ use super :: my_module :: transformer ;
4937 use super :: Command ;
5038
5139 #[ test]
5240 fn it_works ( ) {
53- let output = transformer ( vec ! [
41+ let output = transformer ( & vec ! [
5442 ( "hello" . into( ) , Command :: Uppercase ) ,
5543 ( " all roads lead to rome! " . into( ) , Command :: Trim ) ,
5644 ( "foo" . into( ) , Command :: Append ( 1 ) ) ,
0 commit comments