Having trouble understanding this code

I'm new to coding working on the chapter 3 exercises in the rust book. I came across this persons code online and I'm confused about part of it. At one point they introduce the variable gift_day and I'm unsure where that comes from or why it works since its not referenced anywhere else in the code

fn main() {

    println!("TWELVE DAYS OF CHRISTMAS");

    for day in 1..13 {
        day_intro(day);// first appears here

        for gift_day in (1..(day + 1)).rev() {
            gift(
                gift_day,
                if gift_day == 1 && day != 1{
                    "and"
                } else {
                    ""
                },
            );
            
        }
    }


}

fn day_intro(n:u32) {

    let day = match n {
        1 => "first",
        2 => "second",
        3 => "third",
        4 => "fourth",
        5 => "fifth",
        6 => "sixth",
        7 => "seventh",
        8 => "eighth",
        9 => "ninth",
        10 => "tenth",
        11 => "eleventh",
        12 => "twelfth",
        _ => "",
        
    };

    println!(
        "\nOn the {} day of christmas\nmy true love sent to me:", day
    );
}

fn gift(n:u32, prefix: &str) {

    let gift_text = match n {
        
        1 => "a partridge in a pear tree",
        2 => "two turtle doves",
        3 => "three french hens",
        4 => "four calling birds",
        5 => "five golden rings",
        6 => "six geese a laying",
        7 => "seven swans a swimming",
        8 => "eight maids a milking",
        9 => "nine ladies dancing",
        10 => "ten lords a leaping",
        11 => "eleven pipers piping",
        12 => "drummers drumming",
        _ =>""
    };

    println!("{}{}", prefix, gift_text);

If anyone understands it (and can help explain it to me like I'm 5 lol) i would really appreciate it

A for loop is allowed to introduce bindings in that position - the variable is created there.

2 Likes

Thank you for the explanation. Will it always assume that it is the same type as one that you have previously annotated?

No, if you've previously defined a variable of the same name it is overridden ("shadowed") for the duration of the for loop. The type is defined by what the iterator (right hand side of the in) returns.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.