概述
rust结构体与c中的结构体类似,都使用关键字struct定义。
如:
struct 结构体名 {
成员1:类型1,
成员2: 类型2,
…
}
结构体定义
struct Building{
location: String,
high: u32,
nubmer: u32,
}
结构体变量对象
let soho = Building {
location: String::from("beijing"),
high: 32,
nubmer: 5,
}
结构体成员变量访问
println!("{}", soho.location);
println!("{}", soho.high);
println!("{}", soho.nubmer);
结构体打印输出
如上,结构体可以使用成员变量的方式打印输出,也可以使用如下方式:
- 导入调试库#[derive(Debug)]
- println 和 print 宏中用 {:?} 占位符输出一整个结构体
- 如果属性较多的话可以使用另一个占位符 {:#?}
如下实例:
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("rect1 is {:?}", rect1);
println!("rect1 is {:#?}", rect1);
}
输出结果:
rect1 is Rectangle { width: 30, height: 50 }
rect1 is Rectangle {
width: 30,
height: 50,
}
结构体方法
面向对象的思想可以在rust中实现,可以使用结构体方法(关键字self),实现结构体的成员访问,如下:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("rect1's area is {}", rect1.area());
}
输出结果:
rect1's area is 1500
结构体关联函数
之所以"结构体方法"不叫"结构体函数"是因为"函数"这个名字留给了这种函数:它在 impl 块中却没有 &self 参数。
这种函数不依赖实例,但是使用它需要声明是在哪个 impl 块中的。
一直使用的 String::from 函数就是一个"关联函数"。
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn create(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
fn main() {
let rect = Rectangle::create(30, 50);
println!("{:?}", rect);
}
运行结果:
Rectangle { width: 30, height: 50 }