pu369com

rust 的奇葩点(.和..)语法小记

1      (.)点运算符

看到类似语句:  let s = "12345".split_terminator("").0;

  编译器提示:error[E0616]: field `0` of struct `SplitTerminator` is private

原来被最后那个0给迷惑了,这个点就是 成员访问 运算符

2    (..)两个点运算符

2.1例:    let s = 1..5;    for i in s{ println!("{:?}", i);  }

叫做 右排除范围 运算符   。类似还有   ..=

2.2例:let employee2 = Employee{ employee_name : String::from("Yiibai"), employee_id: 11, ..employee1 };

叫做  结构体更新语法   意思是把 employee1的字段和值都导入到 employee2中。

2.3 例 :
struct Person<'a>{   
         age: u8,
         name: &'a str,
         grade:u8,
}
fn main() {   
    let person = Person { age: 15, name: &"chen",grade:1};
    if let
     Person {        
         age: person_age @ 13..=19,  
         name:person_name,    
         ..
     } = person
 {
     println!("{} is {} years old.", person_name, person_name);
 }
}

代码中有两处(..),后一个应该叫做 “与剩余部分”的模式绑定吧。还有代码中那个 @ 叫模式绑定(ident @ pat)

还有三个点(...)语法 说是废弃了( deprecated)

  其他的参考官方文档参考:https://kaisery.github.io/trpl-zh-cn/appendix-02-operators.html

另,参考https://zhuanlan.zhihu.com/p/126369292

 

posted on 2021-08-24 18:02  pu369com  阅读(529)  评论(1编辑  收藏  举报

导航