赋值与解构

Destructuring

您可以使用 let 关键字从结构或枚举中获取值。这称为解构,并分别为您提供值。首先一个简单的例子:

struct Person { // make a simple struct for a person
    name: String,
    real_name: String,
    height: u8,
    happiness: bool
}

fn main() {
    let papa_doc = Person { // create variable papa_doc
        name: "Papa Doc".to_string(),
        real_name: "Clarence".to_string(),
        height: 170,
        happiness: false
    };

    let Person { // destructure papa_doc
        name: a,
        real_name: b,
        height: c,
        happiness: d
    } = papa_doc;

    println!("Our four values are: {}, {}, {}, and {}.", d, c, b, a);

}

您可以看到它是向后的。首先,我们说 let papa_doc = Person {fields} 来创建结构。然后我们说 let Person {fields} = papa_doc 对其进行解构。您不必写name:a -您只需写名字。但是这里我们写 name = a 是因为我们想使用变量名 a。现在是一个更大的例子。在这个例子中,我们有一个City结构。我们给它一个新的功能。然后我们有一个process_city_values函数来处理这些值。在函数中,我们仅创建了一个 Vec,但是您可以想象,在对它进行解构之后,我们可以做更多的事情。

struct City {
    name: String,
    name_before: String,
    population: u32,
    date_founded: u32,
}

impl City {
    fn new(name: String, name_before: String, population: u32, date_founded: u32) -> Self {
        Self {
            name,
            name_before,
            population,
            date_founded,
        }
    }
}

fn main() {
    let tallinn = City::new("Tallinn".to_string(), "Reval".to_string(), 426_538, 1219);
    process_city_values(&tallinn);
}

fn process_city_values(city: &City) {
    let City {
        name,
        name_before,
        population,
        date_founded,
    } = city;
        // now we have the values to use separately
    let two_names = vec![name, name_before];
    println!("{:?}", two_names);
}
上一页
下一页