HomePlayground
Solutions
rustlings 5.0.0 quiz2 の解法
カニさん
カニさん
August 08, 2022
1
rustlings 5.0.0 quiz2 の解法

rustlings 5.0 quiz2.rs

pub enum Command {
    Uppercase,
    Trim,
    Append(usize),
}

mod my_module {
    use super::Command;

    // TODO: Complete the function signature!
    pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
        // TODO: Complete the output declaration!
        let mut output: Vec<String> = vec![];
        for (string, command) in input.iter() {
            // TODO: Complete the function body. You can do it!
            match command {
                Command::Uppercase => output.push(string.to_uppercase()),
                Command::Trim => output.push(string.trim().to_string()),
                Command::Append(num) => {
                    let mut new_string = string.clone();
                    for _i in 0..*num {
                        new_string = new_string + "bar";
                    };
                    output.push(new_string);
                },
            }
        }
        output
    }
}

#[cfg(test)]
mod tests {
    // TODO: What to we have to import to have `transformer` in scope?
    use my_module::transformer;
    use super::Command;

    #[test]
    fn it_works() {
        let output = transformer(vec![
            ("hello".into(), Command::Uppercase),
            (" all roads lead to rome! ".into(), Command::Trim),
            ("foo".into(), Command::Append(1)),
            ("bar".into(), Command::Append(5)),
        ]);
        assert_eq!(output[0], "HELLO");
        assert_eq!(output[1], "all roads lead to rome!");
        assert_eq!(output[2], "foobar");
        assert_eq!(output[3], "barbarbarbarbarbar");
    }
}

現時点で Rust 歴数か月の初心者なので、解法に何らかの欠陥があるかもしれません。 あくまでも参考程度に。


タグ

rustlings

関連記事

OpenAI公式Rust言語向けChatGPT APIの使用方法
March 25, 2023
1
© 2023, All Rights Reserved.

初心者向け

RustCoder(推奨)Rust入門(速習)コミュニティ

SNS