Home > Mobile >  Iterating through a list containing structs known at compile-time
Iterating through a list containing structs known at compile-time

Time:06-03

I'm unable to run the following code because I'm trying to index the struct instead of using a hard-coded name. Other languages do this, but Rust doesn't seem to given its nature of not being object oriented. The official book doesn't even have a good way of doing the following:

struct Address {
    number: u32,
    city: String,
}

fn print_an_address()  {

    let Address[0] = {
        number: 1,
        city: "New York",
    }
    println!("{}", address[0]);

}

CodePudding user response:

Rust does have this, you're just not using the right syntax. For example:

#[derive(Debug)]
struct Address {
    number: u32,
    city: String,
}

fn print_an_address() {
    let address = [
        Address {
            number: 1,
            city: "New York".to_string(),
        }
    ];
    
    println!("{:?}", address[0]);
}

The local variable address has the array type [Address; 1] here.

(Playground)

You can easily add more elements. Here we add a second element and iterate over the array instead of fetching a specific index. The type of address here has changed to [Address; 2].

#[derive(Debug)]
struct Address {
    number: u32,
    city: String,
}

fn print_addresses() {
    let address = [
        Address {
            number: 1,
            city: "New York".to_string(),
        },
        Address {
            number: 2,
            city: "Boston".to_string(),
        },
    ];
    
    for i in address {
        println!("{:?}", i);
    }
}

(Playground)

  • Related