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

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

What does a match statement look like in Rust?

问题

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

fn clicking_buttons(&mut self, button_name: String) {
  match button_name.as_str() {
    "button_one" => self.on_btn_one(),
    "button two" => self.on_btn_two(),
    "button three" => self.on_btn_three(),
    "button four" => self.on_btn_four(),
    "button five" => self.on_btn_five(),
    _ => {
      // 处理未匹配的情况,如果需要的话
    }
  }
}

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

英文:

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

fn clicking_buttons(&mut self, button_name: String) {
  if button_name.eq("button_one") {
    self.on_btn_one();
  } else if button_name.eq("button two") {
    self.on_btn_two():
  } else if button_name.eq("button three") {
    self.on_btn_three():
  } else if button_name.eq("button four") {
    self.on_btn_four():
  } else if button_name.eq("button five") {
    self.on_btn_five():
  }
}

How would I write this using that Rust match statement?

答案1

得分: 0

fn btn_one() {
    println!("Button one")
}

fn btn_two() {
    println!("Button two")
}

struct Button {
    name: String,
}

fn main() {
    let button = Button {
        name: String::from("one"),
    };

    match button.name.as_str() {
        "one" => btn_one(),
        "two" => btn_two(),
        _ => println!("Button not found!"),
    }
}
英文:

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

<!-- language: rust -->

fn btn_one() {
    println!(&quot;Button one&quot;)
}

fn btn_two() {
    println!(&quot;Button two&quot;)
}

struct Button {
    name: String,
}

fn main() {
    let button = Button {
        name: String::from(&quot;one&quot;),
    };

    match button.name.as_str() {
        &quot;one&quot; =&gt; btn_one(),
        &quot;two&quot; =&gt; btn_two(),
        _ =&gt; println!(&quot;Button not found!&quot;),
    }
}

<!-- 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:

确定