构造体
对于rust的构造体定义和应用只对于几个特地须要留神的点进行阐明,根本用法就不多叙述。
变量与字段名同名时简写语法
能够间接对应各字段变量名称,不必采纳 字段名:变量名的形式struct Book { name:String, price:f32, pages:u32, author:String, publishingHouse:String,}fn initBook(name:String, price:f32, pages:u32, author:String, publishingHouse:String) -> Book { Book { name, price, pages, author, publishingHouse, }}
援用类型构造体字段
存储援用数据须要加上生命周期,否则会在编译时报错(生命周期下一节阐明)struct DataRef{ elementRef1:&str, //Error:missing lifetime specifier elementRef2:&i32, //Error:missing lifetime specifier}
更改为
struct DataRef<'a> { elementRef1:&'a str, elementRef2:&'a i32,}
就能够编译通过。 其中'a是定义生命周期
构造体间赋值
一个曾经存在的构造体的中的局部信息能够赋值给新的构造体#[derive(Debug)] struct Book { name:String, price:f32, pages:u32, author:String, publishingHouse:String, } let book1 = initBook( String::from("Cray rust"), 88.0, 600, String::from("Jack"), String::from("xxx")); let book2 = Book{ name:String::from("Master rust"), price:96.0, pages: 800, ..book1 }; println!("{:?}", book2); //println!("{:?}", book1); //Error:borrow of partially moved value: `book1`
book1中的作者和出版社信息与book2一样,咱们能够在book2赋值时,通过..book1将book1中的值进行复制。
咱们还要留神一下,
- 如果..book1后咱们再应用book1就会在编译时报错:borrow of partially moved value:
book1
这是因为book1中的author和publishingHouse曾经产生了所有权转移 - 在构造体定义上方有这一句#[derive(Debug)]。这是导入调试库 #[derive(Debug)]
- 在 println!就能够用 {:?} 占位符输入一整个构造体,也能够应用{:#?}优化输入构造体显示
- 如果..book1后咱们再应用book1就会在编译时报错:borrow of partially moved value:
元组构造体
之前曾经介绍过元组,元组构造体就是用元组的形式定义构造体。元组构造体存在的意义就是为了不便。看个例子就明确了,定义坐标地位,色彩等能够简略不便的应用元组构造体struct RGB(u32,u32,u32); struct Position(f32, f32,f32); let Red = RGB(255,0,0); let StartPosition = Position(10.0, 10.0, 0.0); println!("Red({},{},{})", Red.0, Red.1, Red.2); println!("StartPositon({},{},{})", StartPosition.0, StartPosition.1, StartPosition.2);
- 办法
办法与之前介绍的函数相似,只是办法是针对构造体的。
构造体办法的第一个参数是self,不须要申明,self是关键字。
self的应用相似于C++中的this,但不能于C++的this等量齐观。
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn compare(&self, rec:&Rectangle) -> bool { if self.area() > rec.area() { true } else { false } } } let rec1 = Rectangle{width:10, height:10}; let rec2 = Rectangle{width:12, height:9}; println!("Is rec1 larger than rec2:{}", rec1.compare(&rec2));
6.关联函数
函数之前说过,关联函数就是于构造体关联的函数。之前用过String::from("xxx")这个函数,这就是String的关联函数。
关联函数不依赖于实例,能够了解为C++的构造函数。
关联函数一样在impl区域内实现,只是不须要self
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn constructor(width:u32, height:u32) -> Rectangle{ Rectangle{width,height} } fn area(&self) -> u32 { self.width * self.height } fn compare(&self, rec:&Rectangle) -> bool { if self.area() > rec.area() { true } else { false } } } let rec1 = Rectangle::constructor(10, 10); let rec2 = Rectangle::constructor(12, 9);