Exercise: first and last base
Goal
Write two one-line functions: first_base(seq) returns seq[0]; last_base(seq) returns seq[seq.len() - 1]. First contact with slice indexing and u8 (an 8-bit unsigned byte — a whole number from 0 to 255) byte literals like b'A'.
Background
A &[u8] is a slice (a borrowed view) of bytes. Writing seq[0] indexes into the slice and returns the byte at that position; seq[seq.len() - 1] returns the byte at the last position. Both of these are indexing expressions and they will panic (abort the program with an error) if the index is out of bounds — we won’t worry about that here.
Bytes are written as numbers, but for DNA it is more readable to use byte literals: b'A' is exactly the same value as the number 65 (the ASCII code for A). We use byte literals throughout the course because DNA fits in one byte per base — there is no need for the multi-byte machinery of full Unicode strings.
The exercise
Open the starter project:
cd day1/ex-first-last-baseFill in the TODOs in src/main.rs so that all three tests pass. Each function body should be a single expression. Don’t worry about what happens on an empty slice — that case isn’t tested (and would panic).
How to run
From inside day1/ex-first-last-base/:
cargo build # compile
cargo test # run the tests — failing at first
cargo run -- ACGT # run the program with a sample sequenceWhen the tests pass, cargo run -- ACGT should print:
first: A, last: T
Hint
Slice indexing with seq[0] returns the first byte; seq[seq.len() - 1] returns the last. See <[T]>::len for the length method.
fn first_base(seq: &[u8]) -> u8 {
seq[0]
}
fn last_base(seq: &[u8]) -> u8 {
seq[seq.len() - 1]
}Solution
The full reference implementation lives in day1/ex-first-last-base-solution/src/main.rs. Try not to peek until your own version passes all three tests.
Where this leads
The next warm-up moves from reading a slice to building one: you will use a for loop to construct a Vec<u8> (a growable heap-allocated array of bytes) base by base.