Branches
Branching in the three languages.
C++
Rust
Java
const int var = 3;
if(var < 0) {
cout << "Var is < 0" << endl;
} else if(var == 0) {
cout << "Var is 0" << endl;
} else {
cout << "Var is > 0" << endl;
}
switch(var) {
case 1:
cout << "Var is 1" << endl;
break;
case 2:
cout << "Var is 2" << endl;
break;
default:
cout << "Var is unknown" << endl;
}
let var = 3;
if var < 0 {
println!("Var is < 0");
} else if var == 0 {
println!("Var is 0");
} else {
println!("Var is > 0");
}
let gt_0 = if var > 0 { true } else { false };
match var {
1 => println!("Var is 1"),
2 => println!("Var is 2"),
3 => println!("Var is 3"),
_ => println!("Var is unknown"),
}
final int var = 3;
if(var < 0) {
System.out.println("Var is < 0");
} else if(var == 0) {
System.out.println("Var is 0");
} else {
System.out.println("Var is > 0");
}
switch(var) {
case 1:
System.out.println("Var is 1");
break;
case 2:
System.out.println("Var is 2");
break;
case 3:
System.out.println("Var is 3");
break;
default:
System.out.println("Var is unknown");
}
Basic if-then-else
branches in all three languages are essentially the same. Where
C++ and Java do not require { }
if there is only a single expression after the condition,
Rust always requires a code block.
Rust introduces pattern matching with the match
keyword. It can be used much like
switch
in C++ or Java as shown.
Rust also introduces if let
expressions that allow you to set a variable based upon
a condition being true or false.