Rust语言学习笔记(2)

来源:互联网 发布:路由器wifi防蹭网软件 编辑:程序博客网 时间:2024/06/06 21:02

结构体(structs)

结构体有三种形式:
  • 没有成员的单元结构体
  • 有成员但没有名字的元组结构体
  • 有成员而且有名字的普通结构体
// 结构体struct Point {    x: i32,    y: i32,}// 不变绑定let origin = Point { x: 0, y: 0 }; // origin: Pointprintln!("The origin is at ({}, {})", origin.x, origin.y);// 可变绑定let mut point = Point { x: 0, y: 0 };point.x = 5;// 更新语法(update syntax)struct Point3d {    x: i32,    y: i32,    z: i32,}let mut point = Point3d { x: 0, y: 0, z: 0 };point = Point3d { y: 1, .. point };// 元组结构体(tuple structs)struct Color(i32, i32, i32);struct Point(i32, i32, i32);let black = Color(0, 0, 0);let origin = Point(0, 0, 0);// 单元结构体(unit-like structs)struct Electron;let x = Electron;

方法语法(method-syntax)

// 方法语法struct Circle {    x: f64,    y: f64,    radius: f64,}impl Circle {    // 要实现方法调用(method calls)语法,第一个参数必须是self的某种形式    fn area(&self) -> f64 {        std::f64::consts::PI * (self.radius * self.radius)    }    // 通过返回结构体来实现链式方法调用(chaining method calls)    fn grow(&self, increment: f64) -> Circle {        Circle { x: self.x, y: self.y, radius: self.radius + increment }    }    // 通过返回结构体来实现关联函数(associated functions)    fn new(x: f64, y: f64, radius: f64) -> Circle {        Circle {            x: x,            y: y,            radius: radius,        }    }}impl Circle {    // self参数只有不变借用,可变借用和移动这三种形式    fn reference(&self) {       println!("taking self by reference!");    }    fn mutable_reference(&mut self) {       println!("taking self by mutable reference!");    }    fn takes_ownership(self) {       println!("taking ownership of self!");    }}fn main() {    let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };    // 方法调用    println!("{}", c.area());    // 关联函数    let c = Circle::new(0.0, 0.0, 2.0);    // 链式方法调用    let d = c.grow(2.0).area();    println!("{}", d);}

枚举(enums)

枚举其实是一种变体结构
在枚举中可以定义所有三种结构体
// 枚举enum Message {    Quit,    ChangeColor(i32, i32, i32),    Move { x: i32, y: i32 },    Write(String),}let x: Message = Message::Move { x: 3, y: 4 };let m = Message::Write("Hello, world".to_string());let v = Message::ChangeColor(r, g, b);

模式(patterns)匹配(match)

// 匹配常量let x = 1;match x {    1 => println!("one"),    2 => println!("two"),    3 => println!("three"),    _ => println!("anything"),}// 匹配多个模式let x = 1;match x {    1 | 2 => println!("one or two"),    3 => println!("three"),    _ => println!("anything"),}// 匹配结构struct Point {    x: i32,    y: i32,}let origin = Point { x: 0, y: 0 };match origin {    Point { x, y } => println!("({},{})", x, y),}match origin {    Point { x: x1, y: y1 } => println!("({},{})", x1, y1),}match origin {    Point { x, .. } => println!("x is {}", x),}match origin {    Point { y, .. } => println!("y is {}", y),}// 匹配枚举enum Message {    Quit,    ChangeColor(i32, i32, i32),    Move { x: i32, y: i32 },    Write(String),}fn quit() { /* ... */ }fn change_color(r: i32, g: i32, b: i32) { /* ... */ }fn move_cursor(x: i32, y: i32) { /* ... */ }fn process_message(msg: Message) {    match msg {        Message::Quit => quit(),        Message::ChangeColor(r, g, b) => change_color(r, g, b),        Message::Move { x: x, y: y } => move_cursor(x, y),        Message::Write(s) => println!("{}", s),    };}// 匹配中忽略某些值// 匹配Result<R,E>时忽略某些值match some_value {    Ok(value) => println!("got a value: {}", value),    Err(_) => println!("an error occurred"),}// 匹配元组时忽略某些值fn coordinate() -> (i32, i32, i32) {    // generate and return some sort of triple tuple}let (x, _, z) = coordinate();let tuple: (u32, String) = (5, String::from("five"));let (x, s) = tuple; // 匹配时String被移动let (x, _) = tuple; // 匹配时String被忽略// 匹配枚举时忽略某些值enum OptionalTuple {    Value(i32, i32, i32),    Missing,}let x = OptionalTuple::Value(5, -2, 3);match x {    OptionalTuple::Value(..) => println!("Got a tuple!"),    OptionalTuple::Missing => println!("No such luck."),}// 匹配后得到不变引用let x = 5;match x {    ref r => println!("Got a reference to {}", r),}// 匹配后得到可变引用let mut x = 5;match x {    ref mut mr => println!("Got a mutable reference to {}", mr),}// 匹配区间let x = 1;match x {    1 ... 5 => println!("one through five"),    _ => println!("anything"),}let x = ',';match x {    'a' ... 'j' => println!("early letter"),    'k' ... 'z' => println!("late letter"),    _ => println!("something else"),}// 匹配时绑定区间到变量名let x = 1;match x {    e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),    _ => println!("anything"),}// 匹配复杂结构体时绑定某一部分到变量名#[derive(Debug)]struct Person {    name: Option,}let name = "Steve".to_string();let mut x: Option = Some(Person { name: Some(name) });match x {    Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),    _ => {}}// 匹配守卫(guards)即匹配时添加条件限制enum OptionalInt {    Value(i32),    Missing,}let x = OptionalInt::Value(5);match x {    OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),    OptionalInt::Value(..) => println!("Got an int!"),    OptionalInt::Missing => println!("No such luck."),}// 守卫的优先级比多重模式要低let x = 4;let y = false;match x {    4 | 5 if y => println!("yes"),    _ => println!("no"),}
0 0
原创粉丝点击