在 Rust 中,bool
是一種基本型別,代表布林值,只能是 true
或 false
。這種型別廣泛應用在邏輯判斷、條件控制、流程分支中。一個布林值佔用 1 個位元組(byte),也就是 8 個位元(bits)。Rust 使用完整的 1 byte 來儲存布林值,這是出於效能考量。在現代的電腦架構中,訪問單一個 bit 通常比訪問整個 byte 還慢。
fn main() {
let is_handsome = true;
let is_silly = false;
println!("Handsome:{}, Silly:{}", is_handsome, is_silly);
}
輸出結果:
Handsome:true, Silly:false
let age: i32 = 21;
let is_young = age < 35;
println!("{}", is_young); // true
// 檢查整數是否為正或負
println!("{} {}", age.is_positive(), age.is_negative()); // true false
這裡 is_young 是比較表達式的結果。只要你寫了 >、<、==、!= 這些比較符號,Rust 都會產出布林值。
println!("{}", !true); // false
println!("{}", !false); // true
! 是邏輯非(not)運算子,用來翻轉布林值。
let age = 18;
let can_see_rated_r_movie = age >= 18;
let cannot_see_rated_r_movie = !can_see_rated_r_movie;
println!(
"I am {} years old. Can I see this scary movie? {}",
age, can_see_rated_r_movie
); //true
如果年齡 age >= 18,就可以觀看 R 級電影。這裡 !can_see_rated_r_movie 是反向判斷。
以下將介紹 Rust 中的:
==
, !=
)&&
, ||
)char
).is_uppercase()
)println!("{}", "Coke" == "Pepse"); // false
println!("{}", "Coke" != "Pepse"); // true
println!("{}", "Coke" == "coke"); // false(大小寫不同)
println!("{}", 12.0 == 12 as f64); // true(型別相同後可比)
println!("{}", 12.0 == 12.01); // false
✅ 說明:
let purchased_ticket = true;
let plane_on_time = true;
let making_event = purchased_ticket && plane_on_time;
println!("It is {} that I will arrive as expected", making_event);
let user_has_paid_for_subscription = true;
let user_is_admin = true;
let user_can_see_premium_experience = user_has_paid_for_subscription || user_is_admin;
println!(
"Can this user see my site? {}",
user_can_see_premium_experience
);
在 Rust 中:
char 表示一個 Unicode 字元,大小固定為 4 個位元組(4 bytes / 32 bits)
char: 單一 Unicode 字元,例如:'A'、'😄',單一字元,使用單引號
&str: 字串切片,包含多個字元 "Hello"、"你好",字串,使用雙引號 "
let first_initial: char = 'B';
let emoji: char = '🤣';
println!("{} {}", first_initial.is_uppercase(), emoji.is_uppercase());
println!("{} {}", first_initial.is_lowercase(), emoji.is_lowercase());
char
可以做什麼?(常用方法)方法 | 說明 | 範例 |
---|---|---|
.is_alphabetic() |
是否為字母(A~Z / a~z 及 Unicode 字母) | 'A'.is_alphabetic() → true |
.is_numeric() |
是否為數字(0~9)及 Unicode 數字 | '7'.is_numeric() → true |
.is_uppercase() |
是否為大寫英文字母或 Unicode 大寫 | 'R'.is_uppercase() → true |
.is_lowercase() |
是否為小寫英文字母或 Unicode 小寫 | 'r'.is_lowercase() → true |
.len_utf8() |
該字元轉為 UTF-8 所佔的位元組數 | '好'.len_utf8() → 3 |
除了前述檢查是否為大小寫,還有檢查是否為數字、字母等。另外要特別注意,該方法適用於單一 char,不是字串(&str),而Emoji、數字等 非字母 字元會回傳 false