Rust 還沒到1.0,開發很快,請看官方文檔
Rust 結構體可使用 struct Name { field1: T1, field2: T2 [, ...] }
的形式聲明。 T1,T2 表示類型,實例化一個struct也用相似的語法,沒有struct關鍵字,好比Point { x: 1.0, y: 2.0 }
。
Rust 的結構體和C的很是相似,甚至內存佈局也同樣,因此能夠從C程序讀取Rust的struct。
使用mypoint.x
的形式訪問struct的值。函數
struct Point { x: f64, y: f64 }
若是struct的實例是可變的,此實例的字段也都是可變的。
好比佈局
let mut mypoint = Point { x: 1.0, y: 1.0 }; // 可變 let origin = Point { x: 0.0, y: 0.0 }; // 不可變 mypoint.y += 1.0; // `mypoint` 是可變的,字段也是 origin.y += 1.0; // ERROR: assigning to immutable field
match
模式匹配也能夠匹配struct,基本的語法是Name { fieldname: pattern, ... }
:code
match mypoint { Point { x: 0.0, y: yy } => println!("{}", yy), Point { x: xx, y: yy } => println!("{} {}", xx, yy) }
在對struct的模式匹配中,你可能不須要全部的字段,可使用 ..
( Name { field1, .. }
)忽略其餘的字段。例如:內存
match mypoint { Point { x, .. } => println!("{}", x) }
一個簡單的枚舉類型定義:開發
enum Direction { North, East, South, West }
其中North 是 0, East 是 1, South 是 2, and West 是 3. 默認值是先前的值加一。
使用as
能夠把North 轉爲int文檔
println!( "{:?} => {}", North, North as int );
指定常量值:it
enum Color { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff }
更復雜的狀況:io
enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
Circle
包含了一個Point
結構體和一個f64,Rectangle
包含了兩個Point
結構體。
聲明定義了類型Shape
,Shape
指的是一個·Shape
類型外加兩個函數Circle
和Rectangle
用來構造該類型的值。
建立新的Circle,這樣寫Circle(Point { x: 0.0, y: 0.0 }, 10.0)
固然也能夠進行模式匹配,訪問枚舉實例值的惟一方式是解構。例如:table
use std::f64; fn area(sh: Shape) -> f64 { match sh { Circle(_, size) => f64::consts::PI * size * size, Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y) } }
使用_
忽略個別字段,忽略全部的字段使用Circle(..)
。
枚舉的模式匹配:ast
fn point_from_direction(dir: Direction) -> Point { match dir { North => Point { x: 0.0, y: 1.0 }, East => Point { x: 1.0, y: 0.0 }, South => Point { x: 0.0, y: -1.0 }, West => Point { x: -1.0, y: 0.0 } } }
枚舉變量也能夠是struct,例如:
use std::f64; enum Shape { Circle { center: Point, radius: f64 }, Rectangle { top_left: Point, bottom_right: Point } } fn area(sh: Shape) -> f64 { match sh { Circle { radius: radius, .. } => f64::consts::PI * square(radius), Rectangle { top_left: top_left, bottom_right: bottom_right } => { (bottom_right.x - top_left.x) * (top_left.y - bottom_right.y) } } }
元組(Tuples)有點相似struct,不過元組的字段是沒有名字的。你也不能經過點來訪問字段。
元組能夠有任意個元素,沒有0個元素的狀況(()
若是你喜歡,能夠看成空元組)。
let mytup: (int, int, f64) = (10, 20, 30.0); match mytup { (a, b, c) => info!("{}", a + b + (c as int)) }
Rust 提供了tuple structs
,元組和結構體的結合。tuple structs
是有名字的(Foo(1, 2)的類型和Bar(1, 2)的不同)。tuple structs
的字段沒有名字。
例如:
struct MyTup(int, int, f64); let mytup: MyTup = MyTup(10, 20, 30.0); match mytup { MyTup(a, b, c) => info!("{}", a + b + (c as int)) }
有個特例是隻有一個字段的tuple structs
,能夠稱做newtypes
(相似Haskell裏的"newtype"特性)。用來建立新的類型,而不是一種類型的別名而已。
struct GizmoId(int);
像這種類型定義對於區分基礎類型同樣,可是用途不同的數據是頗有用的。
struct Inches(int); struct Centimeters(int);
上邊的定義能夠以一個簡單的方式避免混淆不一樣單元的數字。整型值能夠用模式匹配:
let length_with_unit = Inches(10); let Inches(integer_length) = length_with_unit; println!("length is {} inches", integer_length);