定义结构
可以定义成类似于 JS 中的 Object 。
#[derive(Debug)]struct User {name: String,age: u8,description: String,}fn build_user() -> User {User {name: String::from("axes"),age: 10,description: String::from("cool guy"),}}fn main() {let user = build_user();println!("{:?}, {}: {}", user, user.name, user.description);}
使用
{:?}+#[derive(Debug)]声明是为了能让 struct 能够正确打印出来。如果使用{:#?}打印的效果就类似于 JS 中的JSON.stringify(xxx, null, 2),是带缩进的。
定义 tuple
也可以定义成 tuple struct
struct Color(i32, i32, i32);struct Point(i32, i32, i32);let black = Color(0, 0, 0);let origin = Point(0, 0, 0);
定义方法
可以针对 struct 定义方法。
struct Retangle {width: u32,height: u32,}impl Retangle {fn area(&self) -> u32 {self.width * self.height}fn can_hold(&self, other: &Retangle) -> bool {self.width > other.width && self.height > other.height}fn new(width: u32, height: u32) -> Retangle {Retangle {width: width,height: height,}}}fn main() {let rt = Retangle {width: 100,height: 30,};println!("{}", rt.area());let rt2 = Retangle::new(10, 20);println!("{}", rt2.area());println!("{}", rt.can_hold(&rt2));}
可以通过 impl这个关键词定义方法,定义的方法如果首个入参是 &self 那么该方法会认为是 struct 这个实例的方法,否则会认为是 static method ,即与实例无关的。
两种调用的语法不同,前者是用 . 后者是用 :: ,就像平时习惯用的 String::from("xxx"),这种一般用于上面代码中那样来创建 struct 。
在 c/c++ 中,调用 struct 实例的方法会区分是通过实例调还是通过指针调,如果是实例调是
xxx.xx,如果通过指针调是xxx->xx,但是在 rust 中会自动识别当前是实例还是指针,自动选择合适的方式来调用,也就是上面的代码中&rt.area()跟rt.area()是等价的。
