gpt4 book ai didi

string - 如何将结构中的字符串与文字进行模式匹配

转载 作者:行者123 更新时间:2023-11-29 08:11:37 25 4
gpt4 key购买 nike

在我下面的代码中,我发现 match_num_works() 中的代码具有一定的优雅性。我想用类似的公式编写一个 String 匹配项,但无法让它工作。我最终得到了不太优雅的 match_text_works()

struct FooNum {
number: i32,
}

// Elegant
fn match_num_works(foo_num: &FooNum) {
match foo_num {
&FooNum { number: 1 } => (),
_ => (),
}
}

struct FooText {
text: String,
}

// Clunky
fn match_text_works(foo_text: &FooText) {
match foo_text {
&FooText { ref text } => {
if text == "pattern" {
} else {
}
}
}
}

// Possible?
fn match_text_fails(foo_text: &FooText) {
match foo_text {
&FooText { text: "pattern" } => (),
_ => (),
}
}

最佳答案

它可能不是“优雅的”或更好的..但一种选择是将条件移动到匹配表达式中:

match foo_text {
&FooText { ref text } if text == "pattern" => (),
_ => ()
}

Working sample: Playpen link .

关于string - 如何将结构中的字符串与文字进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660941/

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