英文:
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!("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!"),
}
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论