代码之家  ›  专栏  ›  技术社区  ›  Swantewit

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

  •  1
  • Swantewit  · 技术社区  · 3 年前

    我需要学习生锈。这看起来很简单,但我还不能思考。

    在文档中,有一项任务是利用歌曲的重复性打印《圣诞十二日》( https://www.azlyrics.com/lyrics/andywilliams/asongandachristmastreethetwelvedaysofchristmas.html ).

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

    但这似乎是不可能的,或者在这门语言中不是很容易,或者我没有得到什么。

    代码:

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

    请帮我调试,或者把我推向正确的方向,而不是输入12个单独的字符串,然后按1:P打印它们

    1 回复  |  直到 3 年前
        1
  •  1
  •   hkBst    3 年前

    这是有效的:

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