391 단어
2 분
불리언 타입
타입 종류
bool
불리언 타입은 참(true) 또는 거짓(false) 두 가지 값만 가질 수 있습니다.
let t: bool = true;let f: bool = false;조건문에서 사용
if, while 같은 조건문에서는 bool 타입만 사용할 수 있습니다.
let is_rust_fun = true;
if is_rust_fun { println!("Rust is fun!");} else { println!("Hmm...");}비교 연산자
비교 연산의 결과는 항상 bool 타입입니다.
assert_eq!(5 > 3, true);assert_eq!(10 <= 2, false);assert_eq!(3 == 3, true);assert_eq!(3 != 4, true);논리 연산자
&&: AND (둘 다 참일 때만 참)||: OR (둘 중 하나라도 참이면 참)!: NOT (값을 반대로)
assert_eq!(true && false, false);assert_eq!(true || false, true);assert_eq!(!true, false);메서드
then
값이 true일 때만 클로저를 실행합니다.
let result = true.then(|| 42);assert_eq!(result, Some(42));
let result = false.then(|| 42);assert_eq!(result, None);then_some
값이 true일 때만 지정한 값을 반환합니다.
assert_eq!(true.then_some("Hello"), Some("Hello"));assert_eq!(false.then_some("Hello"), None);bool ↔ 정수 변환
Rust 표준 라이브러리에서 직접 변환은 지원하지 않지만, 삼항 연산자 비슷하게 if 표현식을 사용할 수 있습니다.
let b = true;let num = if b { 1 } else { 0 };assert_eq!(num, 1);주의할 점
- Rust에는 암시적 형 변환이 없으므로, 정수를 그대로 조건문에 넣으면 컴파일 오류가 발생합니다.
let x = 1;// if x { } // ❌ error: mismatched typesif x != 0 { // ✅ 명시적 비교 필요 println!("non-zero");}이번에 좀 적네요 ㄴㅇㅅ