gpt4 book ai didi

rust - rust 中的链式 if 语句?

转载 作者:行者123 更新时间:2023-12-05 05:49:01 25 4
gpt4 key购买 nike

Swift 语言支持在一行中使用多个 if 语句。

import Foundation

let x: Int? = 7

if let y = x, pow(Double(y), 2) == 49 {
// do something
}

使用rust 了我需要做

let x: Option<i32> = Some(7);
if let Some(y) = x {
if y.pow(2) == 49 {
// do something
}
}

有没有办法像 Rust 中的 Swift 解决方案那样做一些事情?

最佳答案

可以映射之前的操作,然后完全匹配:

if matches!(x.map(|y| y.pow(2)), Some(49)) {
println!("Yeah");
}

或者使用==:

if x.map(|y| y.pow(2)) ==  Some(49) {
println!("Yeah");
}

Playground

关于rust - rust 中的链式 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70725422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com