Перемещение значений массива в вектор в Rust

У Язык программирования Rust есть задача напечатать Двенадцать дней Рождества, используя его повторяемость.

Моя идея заключалась в том, чтобы собрать все подарки в массив и запихнуть их в вектор, который будет печататься от итерации к итерации.

Кажется, что это либо невозможно, либо непросто, либо я чего-то не понимаю.

Код:

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 отдельных строк и печатать их 1 на 1.

Структурированный массив Numpy
Структурированный массив Numpy
Однако в реальных проектах я чаще всего имею дело со списками, состоящими из нескольких типов данных. Как мы можем использовать массивы numpy, чтобы...
T - 1Bits: Генерация последовательного массива
T - 1Bits: Генерация последовательного массива
По мере того, как мы пишем все больше кода, мы привыкаем к определенным способам действий. То тут, то там мы находим код, который заставляет нас...
Что такое деструктуризация массива в JavaScript?
Что такое деструктуризация массива в JavaScript?
Деструктуризация позволяет распаковывать значения из массивов и добавлять их в отдельные переменные.
0
0
67
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Это работает:

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");
    }
}

Большое спасибо! Возможно, есть более компактный подход для получения аналогичного эффекта на этом языке?

Swantewit 08.05.2022 20:30

@Swantewit Вы имеете в виду итерацию по индексу, как, кажется, вы хотели сделать в своем вопросе? Вы бы сделали for day in 0..presents.len()

kmdreko 08.05.2022 20:55

Окончательный ответ выглядит так (можно добавить все стихи до 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")
    }
}

Другие вопросы по теме