将数组值推送到 Rust 中的向量

Pushing array values to a vector in Rust

Rust 编程语言 有一个任务要打印 The Twelve Days of Christmas 利用它的重复性。

我的想法是将所有礼物收集到一个数组中,并将它们推送到向量中,该向量将在迭代中打印出来。

看来要么是不可能,要么是不容易,要么就是什么都不懂。

代码:

fn main() {
    let presents = [
        "A song and a Christmas tree",
        "Two candy canes",
        "Three boughs of holly",
    ];

    let mut current_presents = Vec::new();

    for day in presents {
        current_presents.push(presents[day]);
        println!(
            "On the {} day of Christmas my good friends brought to me",
            day + 1
        );
        println!("{current_presents} /n");
    }
}
error[E0277]: the type `[&str]` cannot be indexed by `&str`
  --> src/main.rs:11:31
   |
11 |         current_presents.push(presents[day]);
   |                               ^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[&str]>` is not implemented for `&str`
   = note: required because of the requirements on the impl of `Index<&str>` for `[&str]`

error[E0369]: cannot add `{integer}` to `&str`
  --> src/main.rs:14:17
   |
14 |             day + 1
   |             --- ^ - {integer}
   |             |
   |             &str

error[E0277]: `Vec<_>` doesn't implement `std::fmt::Display`
  --> src/main.rs:16:20
   |
16 |         println!("{current_presents} /n");
   |                    ^^^^^^^^^^^^^^^^ `Vec<_>` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Vec<_>`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

请帮助我调试或推动我朝着正确的方向前进,而不是输入 12 个单独的字符串并逐一打印它们。

这个有效:

fn main() {
    let presents = [
        "A song and a Christmas tree",
        "Two candy canes",
        "Three boughs of holly",
    ];

    let mut current_presents = Vec::new();

    for (day, present) in presents.iter().enumerate() {
        current_presents.push(present);
        println!(
            "On the {} day of Christmas my good friends brought to me",
            day
        );
        println!("{current_presents:?}\n");
    }
}

最后的答案是这样的(你可以把所有的经文加到第 12 个):

fn main() {
    let presents = [
        "A song and a Christmas tree",
        "Two candy canes",
        "Three boughs of holly",
        "Four coloured lights",
    ];

    for (day, _) in presents.iter().enumerate() {
        let mut presents = presents;

        let current_presents = &mut presents[0..day + 1];

        println!(
            "On the {} day of Christmas my good friends brought to me",
            day + 1
        );

        current_presents.reverse();

        current_presents
            .iter()
            .for_each(|present| print!("{} \n", present));
        println!("\n")
    }
}