Characters and bytes in Rust
A char is a Unicode scalar; bytes are something else, and Rust keeps them apart.
fn main() {
let word = "Rust!";
println!("{} chars, {} bytes", word.chars().count(), word.len());
for c in word.chars() {
if c.is_alphabetic() {
print!("{}", c.to_ascii_uppercase());
}
}
println!();
let digit = '7';
println!("{:?}", digit.to_digit(10));
}
How it works
chars()walks scalars,bytes()walks the UTF-8 bytes.is_alphabeticand friends classify a char.to_ascii_uppercaseavoids the locale question entirely.
Keywords and builtins used here
fnforifinletmain
The run, in numbers
- Lines
- 14
- Characters to type
- 257
- Tokens
- 90
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 68 seconds.
Step 6 of 6 in Variables & types, step 6 of 39 in Language basics.