在Rust中,”match”语句是什么样的?

huangapple go评论107阅读模式
英文:

What does a match statement look like in Rust?

问题

我是新手 Rust 和 GTK,编写了一个包含长 if/else if 语句的函数,如下所示:

  1. fn clicking_buttons(&mut self, button_name: String) {
  2. match button_name.as_str() {
  3. "button_one" => self.on_btn_one(),
  4. "button two" => self.on_btn_two(),
  5. "button three" => self.on_btn_three(),
  6. "button four" => self.on_btn_four(),
  7. "button five" => self.on_btn_five(),
  8. _ => {
  9. // 处理未匹配的情况,如果需要的话
  10. }
  11. }
  12. }

使用 Rust 的 match 语句,可以更清晰地处理多个条件,以及提供一个默认的 _ 分支来处理未匹配的情况。

英文:

I am new to Rust and GTK and wrote a function with a long if/else if statement like so:

  1. fn clicking_buttons(&mut self, button_name: String) {
  2. if button_name.eq("button_one") {
  3. self.on_btn_one();
  4. } else if button_name.eq("button two") {
  5. self.on_btn_two():
  6. } else if button_name.eq("button three") {
  7. self.on_btn_three():
  8. } else if button_name.eq("button four") {
  9. self.on_btn_four():
  10. } else if button_name.eq("button five") {
  11. self.on_btn_five():
  12. }
  13. }

How would I write this using that Rust match statement?

答案1

得分: 0

  1. fn btn_one() {
  2. println!("Button one")
  3. }
  4. fn btn_two() {
  5. println!("Button two")
  6. }
  7. struct Button {
  8. name: String,
  9. }
  10. fn main() {
  11. let button = Button {
  12. name: String::from("one"),
  13. };
  14. match button.name.as_str() {
  15. "one" => btn_one(),
  16. "two" => btn_two(),
  17. _ => println!("Button not found!"),
  18. }
  19. }
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: rust -->

  1. fn btn_one() {
  2. println!(&quot;Button one&quot;)
  3. }
  4. fn btn_two() {
  5. println!(&quot;Button two&quot;)
  6. }
  7. struct Button {
  8. name: String,
  9. }
  10. fn main() {
  11. let button = Button {
  12. name: String::from(&quot;one&quot;),
  13. };
  14. match button.name.as_str() {
  15. &quot;one&quot; =&gt; btn_one(),
  16. &quot;two&quot; =&gt; btn_two(),
  17. _ =&gt; println!(&quot;Button not found!&quot;),
  18. }
  19. }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 08:30:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定