编程语言结构体struct-Rust
xiu定义struct
使用struct关键字定义名称,大括号内定义属性的名称和类型,以逗号分割每一个属性,最后一个属性也要加上逗号
使用struct需要实例化,赋值的时候顺序可以无序,但是需要写明属性名称
使用结构体属性的数值只需要加点即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| struct xiu { name:String, age:i32, }
fn main() {
let xu = xiu{name:String::from("xu"),age:18};
println!("{}{}",xu.name,xu.age);
}
|
如果需要修改struct的值就需要加上mut关键字,这时候整个struct属性都是可变的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| struct xiu { name:String, age:i32, }
fn main() {
let mut xu = xiu{name:String::from("xu"),age:18};
println!("{}{}",xu.name,xu.age);
xu.age=20;
println!("{}{}",xu.name,xu.age);
}
|
struct可以作为函数返回值
当字段名字和函数参数一致时,可以简写初始化字段值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| struct xiu { name:String, age:i32, }
fn build_xiu(name:String,age:i32)->xiu{
xiu { name, age, }
}
fn main() {
let xu =build_xiu(String::from("xu"), 18);
println!("{}{}",xu.name,xu.age);
}
|
tuple struct
适用于想给某个tuple起名,但是不需要为属性起名

计算长方形面积
最简单的长乘宽的函数,先编写一个简易的

我们可以使用结构体声明长方形

打印结构体
1 2 3 4 5 6 7 8 9 10 11
| struct cfx{ length:u32, width:u32, }
fn main() { let cfx1 = cfx{length:30,width:50};
println!("{}",cfx1);
}
|


1 2 3 4 5 6 7 8 9 10 11 12
| #[derive(Debug)] struct cfx{ length:u32, width:u32, }
fn main() { let cfx1 = cfx{length:30,width:50};
println!("{:?}",cfx1);
}
|
定义方法
方法具有很强的关联性,方法一般定义在struct、enum、trait的上下文中
impl关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #[derive(Debug)] struct cfx{ length:u32, width:u32, }
impl cfx { fn area(&self) -> u32{ self.length*self.width } }
fn main() { let cfx1 = cfx{length:30,width:50};
println!("{}",cfx1.area());
}
|
关联函数
String::from
就是关联函数
不把self作为第一个参数
关联函数通常用于构造器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #[derive(Debug)] struct cfx{ length:u32, width:u32, }
impl cfx { fn area(&self) -> u32{ self.length*self.width }
fn zfx(size:u32)->cfx{ cfx{width:size, length:size} }
}
fn main() { let zfx1 = cfx::zfx(30);
println!("{}",zfx1.area());
}
|

方法与函数的区别
函数(Function)和方法(Method)都是执行代码的代码块,
定义位置:
函数:可以在模块的任何地方定义,与特定的类型无关。
方法:必须定义在impl块中,与特定的类型相关联。
第一个参数:
函数:不自动接收任何参数。
方法:第一个参数总是self,它代表调用该方法的实例。
调用方式:
函数:可以直接调用,例如 my_function(arg1, arg2)
方法:需要通过实例调用,例如 instance.my_method(arg1, arg2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| struct Rectangle { width: u32, height: u32, }
fn area_of_rectangle(width: u32, height: u32) -> u32 { width * height }
impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
fn main() { let rect = Rectangle { width: 10, height: 20 };
let area = area_of_rectangle(10, 20); println!("Area of rectangle using function: {}", area);
let area = rect.area(); println!("Area of rectangle using method: {}", area); }
|
