// bool 변수 선언letthe_true=true;letthe_false:bool=false;// 명시적 타입 어노테이션
연산
bool 논리 연산
&& : AND 연산
|| : OR 연산
! : NOT 연산
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bool 논리 연산letbool_and=true&&false;letbool_or=true||false;letbool_not=!true;println!("AND: {}",bool_and);>>AND:falseprintln!("OR: {}",bool_or);>>OR:trueprintln!("NOT: {}",bool_not);>>NOT:false
단락 평가
bool 연산은 단락평가(short-circuit evaluation) 을 수행한다.
단락평가란, 두 개 이상의 bool 값을 이용한 논리연산에서 결과가 정해지면, 나머지 연산을 생략하는 것이다.
예를 들어, 거짓인 a 와 참인 b를 AND 연산을 하면, a 만 연산을 하고, b는 연산을 하지 않는다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fnsome_func()->bool{println!("This is some func!!");// 이 함수가 실행되면 문구 출력true// true 값을 반환}fnmain(){/* try 1 */letshort_circuit_eval=true&&some_func();println!("short circuit eval : {}",short_circuit_eval);// >> This is some func!!// >> short circuit eval : true/* try 2 */letshort_circuit_eval=false&&some_func();println!("short circuit eval : {}",short_circuit_eval);// >> short circuit eval : false}
위 예시를 살펴보자
some_func()는 "This is some func!!"을 출력하고 true를 반환한다.
try 1에서는 출력이 발생한 것으로 보아, some_func()가 실행되었다.
try 2에서는 출력이 없으므로, 함수가 실행되지 않은 것을 알 수 있다.
이는 AND 연산에서 앞 항이 false면 뒷 항을 평가하지 않기 때문이다.
이에 some_func()는 생략되었고, 출력도 없었던 것이다.
비트 연산
boolean 값들도 비트연산이 가능하다.
그 이유는, ture 와 false 가 각각 0b000001, 0b000000 값을 가지기 때문이다.
Comments