Home > Blockchain >  Pushing Array values to a Vector in Rust
Pushing Array values to a Vector in Rust

Time:05-09

I need to learn Rust. It seems quite straightforward, but I can't think in it yet.

In the documentation there is a task to print "The Twelve Days of Christmas" song taking advantage of its repetitiveness ( https://www.azlyrics.com/lyrics/andywilliams/asongandachristmastreethetwelvedaysofchristmas.html ).

My idea was to gather all the presents in an array and push them to the vector which would be printed from iteration to iteration.

But it seems that it's either impossible, or not really easy in this language or I don't get something.

The code:

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

Please help me debug, or push me in the right direction that wouldn't be typing down 12 separate strings and printing them 1 by 1 :P

CodePudding user response:

This works:

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