728x90
반응형
If문
조건은 반드시 boolean 값이어야하고 그렇지 않으면 에러가 발생한다.
let number = 7;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
// condition was false
if number {
println!("number was three");
}
// ERROR
|
1 | if number {
| ^^^^^^ expected `bool`, found integer
1) if else if
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
2) let구문에서 사용하기
let condition = true;
let number = if condition { 5 } else { 6 };
* 이때 조건에 따른 값은 동일해야 한다. 예를 들어 if 구문에 5, else 구문에 'six'문자열이 들어가게 되면 에러가 발생한다.
let number = if condition { 5 } else { "six" };
// ERROR
|
1 | let number = if condition { 5 } else { "six" };
| - ^^^^^ expected integer, found `&str`
| |
| expected because of this
Loop
러스트의 반복문에는 loop, while, for 세 가지가 있다.
loop에서 조건문을 달아주지 않으면 무한루프에 빠지게 되니 주의해야 한다.
1) 단일 루프
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
2) 멀티 루프
이중 반복문에서 내-외부 종료 시점을 설정해준다.
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2
While 조건부 루프
3
2
1
For
the value is 10
the value is 20
the value is 30
the value is 40
the value is 50
3
2
1
LIFTOFF!
* (1..4) → 1, 2, 3
* (1..4). rev() → 3, 2, 1
728x90
반응형
'Language > Rust' 카테고리의 다른 글
[Rust]소유권 - referrence, borrowing (0) | 2022.12.28 |
---|---|
[Rust]Ownership 소유권 (0) | 2022.12.23 |
[Rust]Functions:Statements&Expressions (0) | 2022.12.22 |
[Rust]데이터타입 (0) | 2022.12.22 |
[Rust] 변수 & 상수 (0) | 2022.12.20 |