枚举可以带方法,本身没什么特别之处:
enum Pet {
Orca
}
enum HttpStatus{
Ok = 200
}
元组型变体:
#[derive((Copy,Clone, Debug, PartialEq))]
enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32)
}
#[derive(Debug)]
struct Account<'a> {
name : String,
language : String,
num: &'a i32
}
struct Ui{}
impl Ui {
pub fn new() -> Ui{
Ui{}
}
pub fn greet(&self, name: &String, language: &String) {
print!("{}{}", name, language);
}
pub fn show_setting(&self, account: Account) {
print!("{:?}", account);
}
}
#[test]
fn account_test() {
let account = Account {name:"good".to_string(), language:"china".to_string(), num:&32};
let ui = Ui::new();
match account {
//局部变量name和language是对account中相应字段的引用。由于account只是被借入而没有被消耗,因此继续调用它的方法是没有问题的。
Account{ref name, ref language, num, ..} => {
ui.greet(name, language);
ui.show_setting(account);
println!("{}", num)
}
}
}
struct Engine {
horsepower: u32,
}
struct CarA {
engine: Engine,
color: String,
}
#[test]
fn reference_model(){
let x = 5;
let y = &x;
match y {
&val => println!("Got a value: {}", val),
}
}
#[test]
fn car_test(){
let car = CarA {
engine: Engine { horsepower: 300 },
color: String::from("Red"),
};
let car_option = Some(&car);
match car_option {
Some(&CarA { ref engine, .. }) => {
println!("The car's engine has {} horsepower.", engine.horsepower);
}
None => {
println!("No car found.");
}
}
}
enum ShapeA {
Rect(Point, Point),
Circle(Point, u32),
// 可能还有其他形状...
}
#[test]
fn main_a() {
let rect = ShapeA::Rect(Point{x:2.0, y:3.0}, Point{x:2.0, y:3.0});
match rect {
rect @ ShapeA::Rect (..) => {
optimized_paint(&rect);
print!("matched");
},
_ => println!("not matched")
};
}
// 假设的 optimized_paint 函数
fn optimized_paint(shape: &ShapeA) {
// 实现细节...
}
fn main() {
let x = 5;
let y = &x;
match y {
ref val => println!("Got a reference to value: {}", val),
}
}