结构体例子

普通函数示例

fn main() {
    let mut w: i32 = 10;
    let h:i32 = 5;
    let area1 = area(w,h);
    println!("Area of rectangle is {}",area1);
    println!("{}", w);
    w = 20;
    let area2 = area(w,h);
    println!("Area of rectangle is {}",area2);
    println!("{}", w);
}

fn area(w:i32, h:i32) -> i32 {
    w*h
}

元组类型示例

fn main() {
    let rect:(i32, i32) = (10, 20);
    println!("The area of the rectangle is {}", area(rect));
}

fn area(dim:(i32, i32)) -> i32 {
    dim.0 * dim.1
}

结构体类型示例

struct Rectangle{
    width: i32,
    height: i32
}
fn main() {
    let rect = Rectangle{width: 30, height: 50};
    println!("The area of the rectangle is {}", area(rect));
}

fn area(rect:Rectangle) -> i32 {
    rect.width * rect.height
}

打印结构体

struct Rectangle{
    width: i32,
    height: i32
}
fn main() {
    let rect = Rectangle{width: 30, height: 50};
    println!("The area of the rectangle is {}", area(rect));
    println!("{}", rect);
}

fn area(rect:Rectangle) -> i32 {
    rect.width * rect.height
}

上面代码会报错 :

`Rectangle` cannot be formatted with the default formatter
help: the trait `std::fmt::Display` is not implemented for `Rectangle`

意思是没有实现 display 方法。 在 rust 中,标准数据类型默认都实现了 display 和 debug 方法,打印自定义结构体需要实现自定义结构体的 display 和 debug 方法。

#[derive(Debug)]
struct Rectangle{
    width: i32,
    height: i32
}
fn main() {
    let rect = Rectangle{width: 30, height: 50};
    println!("The area of the rectangle is {}", area(&rect));
    println!("{:?}", rect);
}

// 使用使用 & 获取一个引用
// 如果不使用 &,rect 的所有权将被移动到函数中,
// 函数结束后,rect 将无法使用
fn area(rect:&Rectangle) -> i32 {
    rect.width * rect.height
}