初面网初面网

结构体

rust里的结构体可以是元组结构,也可以是经典C结构,也可以是无字段的单元结构。

结构体使用驼峰命名。

// 经典C结构
struct Info{
  name: String,
  gender: u8,
  age: u32
}

// struct仅用来定义,结尾不需要分号,字段定义用逗号相隔

// 实例化
let age = 18;
let userinfo = Info{
  name: String::from("Tom"),
  gender: 1,   // 1男, 2女
  age   // 由于上面有age的声明,所以此处可以简化
};

let userinfo2 = Info{
  name: String::from("Jerry"),
  ..userinfo    // 不可以有逗号,至少要改变一个成员
};

元组结构体,可以作为简单的类型定义

struct Color(u8,u8,u8);

let white = Color(255,255,255);
print!("{}", white.0);

结构体在失效时会释放所有字段,所以一般不在结构体中写引用型字段。如果必须在结构体中使用引用型字段,可以通过"生命周期"机制来实现。

想完整输出结构体可以如下书写:

#[derive(Debug)]    // 派生属性。注意Debug的大小写

struct Box{
  width: u8,
  height: u8,
  length: u8
}

let box01 = Box{width: 30, length: 30, height: 30};
println!("{:?}", box01);  // 注意花括号内的写法。输出Box { width: 30, length: 30, height: 30 }

结构体方法的实现和使用如下

struct Box{
  width: u8,
  height: u8,
  length: u8
}

impl Box{
  fn volume(&self) -> u8 {
    self.width * self.height * self.length
  }
}

let box01 = Box{width: 2, length: 2, height: 2};
println!("Box Volume is {}", box01.Volume());

多参数的情况:

struct Box{
  width: u8,
  height: u8,
  length: u8
}

impl Box{
  fn volume(&self) -> u8 {
    self.width * self.height * self.length
  }

  fn wider(&self, rect: &Box) -> bool {
    self.width > rect.width
  }
}

let box01 = Box{width: 2, length: 2, height: 2};
let box02 = Box{width: 3, length: 3, height: 3};
println!("box01 wider than box02 is {}", box01.wider(&box02));

结构体函数:在impl块中没有&self参数的

#[derive(Debug)]
struct Box{
  width: u8,
  height: u8,
  length: u8
}

impl Box {
  fn create(width: u8, height: u8, length: u8) -> Box {
    Box { width, height, length }
  }
}

let rect = Box::create(2, 2, 2);
println!("{:?}", rect);

impl可以多写几次,内容会自动拼接

单元结构体:没有成员的结构体,一般用于泛型。

struct Box;

let the_box = Box;

更新于 2026/6/10