遍历包含编译时已知结构的列表

Iterating through a list containing structs known at compile-time

我无法 运行 以下代码,因为我正在尝试索引结构而不是使用硬编码名称。其他语言也这样做,但 Rust 似乎并没有给出其非面向对象的性质。官方书上连下面的好方法都没有:

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

fn print_an_address()  {

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

}

Rust 确实有这个,你只是没有使用正确的语法。例如:

#[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]);
}

局部变量address这里是数组类型[Address; 1]

(Playground)

您可以轻松添加更多元素。这里我们添加第二个元素并遍历数组而不是获取特定索引。这里address的类型变成了[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)