【问题标题】:What does "let" do in Rust?\"let\" 在 Rust 中做什么?
【发布时间】:2023-02-23 08:40:20
【问题描述】:

主要是两个问题:

  1. let x = y如何翻译成伪英文/伪代码?
  2. if let x = y {} 块如何逐步工作?

    总是假设声明一个变量,直到我遇到如果让(下面的代码),然后去谷歌搜索。

    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("The maximum is configured to be {}", max);
    } else {
        println!("xyz");
    }
    

    StackOverflow 线程解释说实际上评估/检查模式.所以我把它理解为 let 只检查模式和值是否匹配,而不是自己声明变量:

    let y = Some(5);
    if let Some(x) = y { doZ(x); }
    // 1. let Some(x) = y -- see if pattern Some(x) matches value y, if yes execute next expression
    // 2. Some(x) = y -- the next expression, assign value of y to "variable Some(x)"
    // if ( 1 and 2 are successful) { execute this }
    

    但是,如果只用于模式-值匹配/求值,那为什么用在变量声明中呢? 答:因为它不仅用于模式匹配,而且还需要用于变量声明。

    let y = Some(5);
    if let Some(x) = y { doZ(x); }
    // if -- if
    // let Some(x) = y -- ( if pattern Some(x) matches Some(5), declare variable Some(x) and assign value Some(5) to it ) 
    // doZ(x) -- { execute doZ function and pass x as an argument}
    

    a - 上面的“翻译”是否意味着let Some(x) = Some(5) == let x = 5?如果是,那是怎么发生的? b - Option<T>Enum 类型的重点不是与原始T 不同吗?

    if let x = 5 { doZ(x); } // a
    // Warning: x = 5 is irrefutable, consider using just "let" without "if".
    
    5 == Some(5) // b, false
    

    上面的错误也反驳了if let Some(x) = y中的ifif是一个正则if,寻找一个bool值,之后会运行“{}”里面的代码。但是 let 是一个语句,它不返回 bool 或任何东西,有或没有 if。那么这是否意味着在这种特定情况下if实际上不是if(需要一个布尔值来执行代码),而是一个耗尽的match?如果是,为什么是 if 而不是其他/新关键字?

【问题讨论】:

  • 您最后的“错误”不是错误,而是警告,不需要 if
  • let 本身声明了一个变量。 if let 使用绑定进行模式匹配。
  • let 本身也做模式匹配,只是无可辩驳的。 @cadolphs
  • 非常好的澄清,是的。这对于元组拆包之类的事情非常有用。
  • @cadolphs,所以if let不能声明一个变量?

标签: rust


【解决方案1】:
  1. let 本身只是变量赋值(如果模式是无可辩驳的,可能与模式匹配)。
  2. if 本身是基于 bool 值的分支
  3. if let 不仅仅是 letif 的一些奇怪的混搭,而是一个单独的结构:

    if let 是做什么的?它尝试将值与模式相匹配,并在这样做时将部分值绑定到正在匹配的模式。只有当模式真正匹配成功时,它才会执行 if let 块中的代码:

    let x = 5; // simple variable assignment
    
    let (x, y) = (3, 4); // assignment with pattern matching
    
    if x % 2 == 0 { // only do this code if number is even
      println!("x is even");
    }
    
    // if let to do pattern-matching and assignment, 
    // but where the pattern might potentially not match
    if let Some(x) = function_that_returns_option() {
      println!("The function returned Some(x) with x = {}", x);
    }
    
    // if the function had returned None instead, then nothing would have been printed and nothing would have been assigned to that x.
    

【讨论】:

  • 它只是一个“按原样接受”的东西还是有其他一些用例?为什么它是一个东西?为什么不是matchLight Some(x) = optionReturn() { println!({x}) }
猜你喜欢
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 2021-03-21
  • 1970-01-01
  • 2021-06-12
  • 2013-09-22
相关资源
最近更新 更多