rust结构体


 //Rust 并不允许只将某个字段标记为可变
 struct User {
        email: String,
        name:String,
        age:i32,
        sex:String,
        active:bool,
 }
fn main() {
    
    let mut user1=User{
        email: String::from("1@qq.com"),
        name:String::from("hehe"),
        age:23,
        sex: String::from("man"),
        active:true,
    };
    user1.name =String::from("zhangsan");

    let user2 = User {
        email: String::from("3@qq.com"),
        name: String::from("lisa"),
        ..user1 //其余值来自 user1 变量中实例的字段,简写形式
    };

    let user3=set_user_value(String::from("2@qq.com"),String::from("xiaohong"));

}

fn set_user_value(email:String,name:String)->User {
    //参数名和结构体的名字相同时,可简写比如email:email 可以直接写email,
    User {
        email,
        name,
        age:23,
        sex:String::from("man"),
        active:true,
    }
}

User 结构体的定义中,我们使用了自身拥有所有权的 String 类型而不是 &str 字符串 slice 类型。
这是一个有意而为之的选择,因为我们想要这个结构体拥有它所有的数据,为此只要整个结构体是有效的话其数据也是有效的。
可以使结构体存储被其他对象拥有的数据的引用,不过这么做的话需要用上 生命周期(lifetimes)

一个示例

//使用结构体的好处组织性

//增加注解来派生 Debug trait,并使用调试格式打印 Rectangle 实例
#[derive(Debug)]
struct Rectangle{
    width:u32,
    height:u32,
}
//impl 块将函数定义在上下文中
impl Rectangle{
    //使用 &self 来替代 rectangle: &Rectangle,
    //因为该方法位于 impl Rectangle 上下文中
    //所以 Rust 知道 self 的类型是 Rectangle
    //加&表示不获取所有权,因为我们使用值就可以了

    //如果想修改里面的值就需要在self前加&mut,然后将
    //let  rect1 改为let mut rect1 
    fn area(&mut self) ->u32{
        self.width = 23;
        self.width*self.height
    }
}
fn main() {
    let mut rect1 = Rectangle{width:30,height:50};
    // {:#?}是比 {:?}风格优美的打印格式
    //println!("rec1 is {:#?}",rect1);
    // println!(
    //     "The area of the rectangle is {} square pixels.",
    //     area(&rect1)
    //     );
    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
        )
}

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

//方法定义,第一参数必须是self。

posted @ 2019-12-03 11:11  公众号python学习开发  阅读(230)  评论(0编辑  收藏  举报