Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

结构体

结构体是用关键字 struct 定义的具名结构体类型

结构体声明在其所在模块或块的类型命名空间中定义给定的名称。

一个 struct 程序项及其使用的示例:

#![allow(unused)]
fn main() {
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 11};
let px: i32 = p.x;
}

元组结构体是具名的元组类型,同样用关键字 struct 定义。除了定义类型外,它还在值命名空间中定义一个同名的构造器。构造器是一个可以调用以创建结构体新实例的函数。例如:

#![allow(unused)]
fn main() {
struct Point(i32, i32);
let p = Point(10, 11);
let px: i32 = match p { Point(x, _) => x };
}

类单元结构体是没有字段的结构体,通过完全省略字段列表来定义。这种结构体隐式定义了一个与其类型同名的常量。例如:

#![allow(unused)]
fn main() {
struct Cookie;
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}

等价于

#![allow(unused)]
fn main() {
struct Cookie {}
const Cookie: Cookie = Cookie {};
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}

结构体的精确内存布局未指定。可以使用 repr 属性来指定特定的布局。