本文簡要介紹rust語言中 Primitive Type bool 的用法。
布爾類型。
bool 表示一個值,它隻能是 true 或 false 。如果將bool 轉換為整數, true 將為 1, false 將為 0。
基本用法
bool 實現了各種特征,例如 BitAnd 、 BitOr 、 Not 等,它們允許我們使用 & 、 | 和 ! 執行布爾運算。
if 需要 bool 值作為其條件。 assert! 是測試中的一個重要宏,它檢查表達式是否為 true ,如果不是,則Panics。
let bool_val = true & false | false;
assert!(!bool_val);例子
bool 用法的一個簡單示例:
let praise_the_borrow_checker = true;
// using the `if` conditional
if praise_the_borrow_checker {
println!("oh, yeah!");
} else {
println!("what?!!");
}
// ... or, a match pattern
match praise_the_borrow_checker {
true => println!("keep praising!"),
false => println!("you should praise!"),
}此外,由於 bool 實現了 Copy 特征,我們不必擔心移動語義(就像整數和浮點原語一樣)。
現在將bool 轉換為整數類型的示例:
assert_eq!(true as i32, 1);
assert_eq!(false as i32, 0);相關用法
- Rust bool.then_some用法及代碼示例
- Rust bool.then用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
- Rust i16.log10用法及代碼示例
- Rust LowerExp用法及代碼示例
- Rust HashSet.get_or_insert_with用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Primitive Type bool。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
