Bitpath

Boss lesson · Unit 03

A text toolkit

Small functions that borrow text and return new text, each one checked

13 exercisesabout 3 min

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?

Rust
for c in "hey".chars() {
    println!("{c}");
}

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.

Rust
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.

Rust
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.

Rust
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.

One email when Bitpath is ready to try. Nothing else. Privacy