Bool and char
- Rust course
- Beginner
- Lesson 15/115
- 4 min
Store logic and characters with bool and char types.
Bool and char
bool takes the values true/false. A char is written with single quotes and is a 4-byte Unicode scalar value; not just ASCII but Turkish letters and emoji are a single char too:
let aktif = true;
let harf = 'ş';
let emoji = '🦀';
println!("{} {} {}", aktif, harf.is_alphabetic(), emoji);Double quotes ("a") make a string, single quotes ('a') a char.
char methods
char offers classification and conversion methods:
let c = '7';
println!("{}", c.is_ascii_digit()); // true
println!("{:?}", c.to_digit(10)); // Some(7)
println!("{}", 'a'.to_ascii_uppercase()); // A
println!("{}", 'A' as u32); // 65Logical operators short-circuit: in a && b, if a is false, b is never evaluated.
Practice Digit sum
Walk every character of the text "4096" with .chars(), convert each with to_digit(10) and sum them. Print the sum.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut toplam = 0;
for c in "4096".chars() {
toplam += c.to_digit(10).unwrap();
}
println!("{}", toplam);
}Expected output
19
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>std::mem::size_of::<char>()</code> return?
- 1
- 2
- 8
- 4 Correct answer
Explanation: A char is 4 bytes so it can hold any Unicode character; inside a string, characters take 1-4 bytes as UTF-8.
2 Convert to a digit
let d = '9'.____(10); // Some(9)
let d = '9'.to_digit(10); // Some(9)
Explanation: to_digit(10) returns a decimal digit as Option<u32>.
3 Expression and result
| Term | Meaning |
|---|---|
'A' as u32 |
65 |
'ş'.is_alphabetic() |
true |
'x'.to_digit(10) |
None |
!true |
false |