Rust 条件语句学习笔记

在 Rust 中,条件语句可以使用 ifif-elseelse ifmatch 等关键字来实现,本文将分别介绍它们的用法和实例。

if 语句

最简单的条件语句是 if 语句,其语法如下:

rustCopy Code
if condition { // 当条件为真时执行的代码块 }

其中的 condition 是一个布尔表达式,当其值为真时,执行花括号内的代码块。下面是一个示例:

rustCopy Code
fn main() { let x = 5; if x == 5 { println!("x is five!"); } }

输出结果为:

Copy Code
x is five!

if-else 语句

if-else 语句可以在条件为假时执行另外一段代码,其语法如下:

rustCopy Code
if condition { // 当条件为真时执行的代码块 } else { // 当条件为假时执行的代码块 }

下面是一个示例:

rustCopy Code
fn main() { let x = 5; if x == 10 { println!("x is ten!"); } else { println!("x is not ten!"); } }

输出结果为:

Copy Code
x is not ten!

else if 语句

else if 语句可以在 ifelse 之间添加多个条件判断,其语法如下:

rustCopy Code
if condition1 { // 当条件1为真时执行的代码块 } else if condition2 { // 当条件2为真时执行的代码块 } else { // 当以上条件均为假时执行的代码块 }

下面是一个示例:

rustCopy Code
fn main() { let x = 5; if x == 10 { println!("x is ten!"); } else if x == 5 { println!("x is five!"); } else { println!("x is not ten or five!"); } }

输出结果为:

Copy Code
x is five!

match 表达式

match 表达式可以根据一个值的不同情况执行不同的分支代码,其语法如下:

rustCopy Code
match value { pattern1 => { // 当 value 匹配 pattern1 时执行的代码块 }, pattern2 => { // 当 value 匹配 pattern2 时执行的代码块 }, _ => { // 当 value 不匹配任何模式时执行的代码块 }, }

其中的 value 是需要匹配的值,pattern1pattern2 是值可能匹配的模式。下面是一个示例:

rustCopy Code
fn main() { let x = 5; match x { 10 => { println!("x is ten!"); }, 5 => { println!("x is five!"); }, _ => { println!("x is not ten or five!"); }, } }

输出结果为:

Copy Code
x is five!

以上就是 Rust 条件语句的使用方法和示例。