常用的语言,表达式语句是语言的组成部分,rust也是一样的。
if语句
和C语言并无区别
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
循环语句
c、c++中的循环有for语句、while语句。
loop语句是rust特定的无限循环语句, 这是新增的语法特性。
let mut x = 5;
loop {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { break; }
}
for语句,虽然rust也有,但是用法和python、go是一致的
for x in 0..10 {
println!("{}", x); // x: i32
}
while语句几种语言并无区别
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
match语句
c和c++中有switch语句,在rust中形态是match语句
let x = 5;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
4 => println!("four"),
5 => println!("five"),
_ => println!("something else"),
}
小结
从语句层面看,rust基本是个综合体,这点各种语言并无太大差别。









网友评论