14.结构体struct.rs

//Rust 里 struct 语句仅用来定义,不能声明实例,结尾不需要 ; 符号,而且每个字段定义之后用 , 分隔

#[derive(Debug)]
struct Site {
    domain: String,
    name: String,
    nation: String,
    found: u32
}

fn main() {
    let runoob = Site {
        domain: String::from("www.runoob.com"),
        name: String::from("RUNOOB"),
        nation: String::from("China"),
        found: 2013
    };
    println!("{:?}",runoob);

    //必须使用key: value 语法来实现定义
    // let runoob2 = Site {
    //     String::from("www.runoob.com"),
    //     name: String::from("RUNOOB"),
    //     nation: String::from("China"),
    //     found: 2013
    // };
    
    //但是,如果正在实例化的结构体有字段名称和现存变量名称一样的,可以简化书写
    let domain = String::from("www.runoob.com");
    let runoob2 = Site {
        domain,
        name: String::from("RUNOOB"),
        nation: String::from("China"),
        found: 2013
    };

    //你想要新建一个结构体的实例,其中大部分属性需要被设置成与现存的一个结构体属性一样,仅需更改其中的一两个字段的值,可以使用结构体更新语法:
    //注意:..runoob 后面不可以有逗号。这种语法不允许一成不变的复制另一个结构体实例,意思就是说至少重新设定一个字段的值才能引用其他实例的值
    let runoob3 = Site {
        nation: String::from("Chinese"),
        .. runoob2
    };
    println!("{:?}",runoob3);

    //元组结构体
    //元组结构体是一种形式是元组的结构体。与元组的区别是它有名字和固定的类型格式。它存在的意义是为了处理那些需要定义类型(经常使用)又不想太复杂的简单数据
    #[derive(Debug)]
    struct Color(u8, u8, u8);
    struct Point(f64, f64);
    let black = Color(0, 0, 0);
    let origin = Point(0.0, 0.0);
    println!("{:?}",black);
    println!("{}-{}",origin.0,origin.1);

    let rect1 = Rectangle { width: 30, height: 50 };
    println!("rect1's area is {}", rect1.area());

    let rect2 = Rectangle { width: 40, height: 20 };
    println!("{}", rect1.wider(&rect2));

    let rect3 = Rectangle::reate(23,32);
    println!("rect3 is {:?}", rect3);

}

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

//结构体方法
impl Rectangle {
    fn area(&self) -> u32{
        self.width * self.height
    }

    fn wider(&self, rect: &Rectangle) -> bool {
        self.width > rect.width
    }
}

//结构体函数(类似C++构造函数)
impl Rectangle {
    fn reate(width:u32, height:u32) -> Rectangle{
        Rectangle{width,height}
    }
}

//单元结构体,结构体可以值作为一种象征而无需任何成员:
struct UnitStruct;

猜你喜欢

转载自blog.csdn.net/liujiayu2/article/details/114387377