Rust
RUST Documentation 따라 공부하기 5
2019.12.30
Control Flow
if
func main() {
let x = 5;
if x < 5 { // condition must be type of boolean
println!("condition true");
} else {
println!("condition false");
}
}
Rust will not automatically try to convert non-Boolean types to a Boolean. You must be explicit and always provide
if
with a Boolean as its condition.
- 너무 많은 else if 는 Rust에서 좋은 방법이 아니다.
- match 를 사용하는게 좋을 수도 있다.
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
let statement에서 if 문으로 값을 초기화 할 수 있다.
The values that have the potential to be results from each arm of the
if
must be the same type.
loops
loop
, while
, for
fn main() {
let mut counter = 0;
// you can add the value you want returned after the break expression you use to stop the loop;
// that value will be returned out of the loop so you can use it, as shown here:
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // will be returned
}
};
loop {
println!("again!");
}
}
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
// 위 코드는 while로 하는 것보다는 for로 하는 것이 훨씬 좋은 방법이다.
// 속도도 빠르고, error 발생(index err) 방지
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
The safety and conciseness of
for
loops make them the most commonly used loop construct in Rust. Even in situations in which you want to run some code a certain number of times, most Rustaceans would use afor
loop.
fn main() {
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!!");
}