< 返回版块

冷石Boy 发表于 2023-10-25 16:02

Tags:rustlings

初学者,被这题难到了orz...


Ext Link: https://github.com/LearningOS/rustlings-100exercises-template/blob/main/exercises/quiz2.rs

评论区

写评论
bestgopher 2023-10-26 10:31

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2ed59f417545b1ce63eb8564a4d9fe7d

作者 冷石Boy 2023-10-25 16:50

赞👍🏻

--
👇
Bai-Jinlin: ```rust pub enum Command { Uppercase, Trim, Append(usize), }

mod my_module { use super::Command; pub fn transformer(input: Vec<(String, Command)>) -> Vec { let mut output: Vec = vec![]; for (string, command) in input.iter() { output.push(match command { Command::Uppercase => string.to_uppercase(), Command::Trim => string.trim().into(), Command::Append(n) => format!( "{}{}", string, std::iter::repeat("bar").take(*n).collect::() ), }); } output } }

#[cfg(test)] mod tests { use super::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");
}

}

Bai-Jinlin 2023-10-25 16:31

这题都能被难到说明基础不到位,看看书再做这些题吧。

Bai-Jinlin 2023-10-25 16:23
pub enum Command {
    Uppercase,
    Trim,
    Append(usize),
}

mod my_module {
    use super::Command;
    pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
        let mut output: Vec<String> = vec![];
        for (string, command) in input.iter() {
            output.push(match command {
                Command::Uppercase => string.to_uppercase(),
                Command::Trim => string.trim().into(),
                Command::Append(n) => format!(
                    "{}{}",
                    string,
                    std::iter::repeat("bar").take(*n).collect::<String>()
                ),
            });
        }
        output
    }
}

#[cfg(test)]
mod tests {
    use super::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");
    }
}
1 共 4 条评论, 1 页