• rust 个例


    fn main() {
    let a = [4,3,2,1];

    // 通过索引和值的方式迭代数组 `a`
    for (i,v) in a.iter().enumerate() {
    println!("第{}个元素是{}",i+1,v);
    }
    }

    ================================================================

    fn main() {
    let names = [String::from("liming"),String::from("hanmeimei")];
    for _name in &names {
    // do something with name...
    }

    println!("{:?}", names);

    let numbers = [1, 2, 3];
    // numbers中的元素实现了 Copy,因此无需转移所有权
    for _n in numbers {
    // do something with name...
    }

    println!("{:?}", numbers);
    }

    =========================================================

    fn main() {
        let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];
    
        // fill the blank with `matches!` to make the code work
        for ab in alphabets {
            assert!(matches!(ab, 'a'..='z' | 'A'..='Z' | '0'..='9'))
        }
    } 

     ==========================================================

    struct Point {
    x: i32,
    y: i32,
    }

    fn main() {
    // 填空,让 p 匹配第二个分支
    let p = Point { x: 1000, y: 1000 };

    match p {
    Point { x, y: 0 } => println!("On the x axis at {}", x),
    // 第二个分支
    Point { x: 0..=5, y: y@ (10 | 20 | 30) } => println!("On the y axis at {}", y),
    Point { x, y } => println!("On neither axis: ({}, {})", x, y),
    }
    }

    ===========================================

    @ 操作符可以让我们将一个与模式相匹配的值绑定到新的变量上

    enum Message {
    Hello { id: i32 },
    }

    fn main() {
    let msg = Message::Hello { id: 5 };

    match msg {
    Message::Hello {
    id: id@( 3..=7),
    } => println!("id 值的范围在 [3, 7] 之间: {}", id),
    Message::Hello { id: newid@(10 | 11 | 12) } => {
    println!("id 值的范围在 [10, 12] 之间: {}", newid);
    }
    Message::Hello { id } => println!("Found some other id: {}", id),
    }
    }

    =============================================

    使用 .. 忽略一部分值

    fn main() {
    let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);

    match numbers {
    (first,..,last) => {
    assert_eq!(first, 2);
    assert_eq!(last, 2048);
    }
    }
    }

    =============================================

    使用模式 &mut V 去匹配一个可变引用时,你需要格外小心,因为匹配出来的 V 是一个值,而不是可变引用

    fn main() {
    let mut v = String::from("hello,");
    let r = &mut v;

    match r {
    _value => _value.push_str(" world!")
    }
    }

  • 相关阅读:
    ES6 随记(1)-- let 与 const
    this 机制的四种规则
    BEM(一种 CSS 命名规则)
    WebSocket 的后记
    WebSocket 初体验
    “空”的艺术-当数据为空时显示什么
    前端路由以及浏览器回退,hash & history & location
    体验 WebFont,网页上的艺术字
    dedecms安装全过程(集成环境)
    面向对象(五)
  • 原文地址:https://www.cnblogs.com/pythonClub/p/16461663.html
Copyright © 2020-2023  润新知