Boss lesson · Unit 03
A text toolkit
Small functions that borrow text and return new text, each one checked
What you practise
- Small functions that borrow text and return new text: a palindrome check, a vowel counter, a Caesar shift, each checked with
assert_eq!
Try a question from this lesson
Pick one
chars() hands out the characters of a text one at a time. How many lines does this print?
for c in "hey".chars() {
println!("{c}");
}Correct answer
3
Why
The loop runs once per character: h, then e, then y. Each round c is one char. A for loop works on anything that can hand out values one by one, not only on ranges of numbers.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A check that speaks only when wrong
How do you know a function is right? Call it with inputs whose answers you know.
assert_eq!(a, b) compares two values. If they are equal, nothing happens. If not, the program stops and shows both.
Silence means every check passed.
fn double(n: i32) -> i32 {
n * 2
}
assert_eq!(double(4), 8);
assert_eq!(double(0), 0);
println!("all checks passed");Concept
Building new text
A function cannot change text it only borrowed. To hand back different text, it builds a new String.
String::new() makes an empty one. push(c) adds one character to its end.
chars().rev() hands the characters out backwards: rev is short for reverse.
let mut out = String::new();
for c in "abc".chars() {
out.push(c);
out.push('-');
}
println!("{out}");Concept
Characters are numbers underneath
The computer stores each character as a number: a is 97, b is 98, and so on up to z at 122.
as u8 turns a char into its number. u8 is a small whole-number type, 0 to 255. as char turns a u8 back.
So moving along the alphabet is plain arithmetic.
let n = 'a' as u8;
println!("{n}");
println!("{}", (n + 2) as char);9 more exercises in the app
- 3× type the answer
- 2× multiple choice
- 2× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.