study Rust-7【使用结构体的demo】

fn main() {
    let width1 = 30;
    let height1 = 50;

    println!(
        "The area of the rectangle is {} square pixels.",
        area(width1, height1)
    );
}

fn area( u32, height: u32) -> u32 {
    width * height
}

继续计算面积:

fn main() {
    let rect1 = (30, 50);

    println!(
        "The area of the rectangle is {} square pixels.",
        area(rect1)
    );
}

fn area(dimensions: (u32, u32)) -> u32 {
    dimensions.0 * dimensions.1
}

在继续计算面积:

struct Rectangle {
     u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {  30, height: 50 };

    println!(
        "The area of the rectangle is {} square pixels.",
        area(&rect1)
    );
}

fn area(rectangle: &Rectangle) -> u32 {
    rectangle.width * rectangle.height
}
/*

这里我们定义了一个结构体并称其为 Rectangle。在大括号中定义了字段 widthheight,类型都是 u32。接着在 main 中,我们创建了一个具体的 Rectangle 实例,它的宽是 30,高是 50。


函数 area 现在被定义为接收一个名叫 rectangle 的参数,其类型是一个结构体 Rectangle 实例的不可变借用。我们希望借用结构体而不是获取它的所有权,这样 main 函数就可以保持 rect1 的所有权并继续使用它,所以这就是为什么在函数签名和调用的地方会有 &


area 函数访问 Rectangle 实例的 widthheight 字段。area 的函数签名现在明确的阐述了我们的意图:使用 Rectanglewidthheight 字段,计算 Rectangle 的面积。这表明宽高是相互联系的,并为这些值提供了描述性的名称而不是使用元组的索引值 01 。结构体胜在更清晰明了。


*/

下面的demo展示如何println:

#[derive(Debug)]
struct Rectangle {
     u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {  30, height: 50 };

    println!("rect1 is {:?}", rect1);
}

输出:
rect1 is Rectangle {  30, height: 50 }
原文地址:https://www.cnblogs.com/usegear/p/14972240.html