Exercise: Complement a single base

Goal

Write a function complement_base(base: u8) -> u8 that returns the Watson–Crick complement of a single DNA base. A pairs with T, C pairs with G, in both upper and lower case. N/n (unknown base) passes through unchanged. Any other byte should make the function panic with a clear message.

This is a single match expression — your first Rust function whose entire body is one expression with no ;.

Background

DNA is double-stranded. Wherever one strand has an A, the complementary strand has a T at the same position; wherever one strand has a C, the other has a G. The function you write today is the inner workhorse of “reverse complement”, which you will assemble on day 2.

Two horizontal DNA strands drawn as light-blue bands holding boxed monospace letters. Top strand left to right: 5 prime A T C G 3 prime. Bottom strand left to right: 3 prime T A G C 5 prime. Between each aligned pair of bases, short black horizontal lines represent hydrogen bonds: two lines for the A-T and T-A columns, three lines for the C-G and G-C columns. Dashed grey connectors point to annotations reading 'A=T: 2 H-bonds' and 'G=C: 3 H-bonds'.
Figure 1: Two antiparallel DNA strands shown column-wise. Read each column top-to-bottom to see the base pair, and count the short horizontal lines between the strands to see the hydrogen-bond count: A=T has two bonds, G=C has three. The 5’ and 3’ end labels show that the two strands point in opposite directions.

The exercise

Open the starter project:

cd day1/ex-complement

src/main.rs contains:

  • A function complement_base(base: u8) -> u8 with a // TODO body
  • A main that takes one character on the command line and prints its complement
  • Eight unit tests covering each base, lower case, the N passthrough, and the invalid-input panic

Make all the tests pass. Do not change the function signature, main, or the tests.

How to run

cargo test                 # one passes, the rest fail
cargo run -- A             # expected output: T
cargo run -- g             # expected output: c
cargo run -- N             # expected output: N

Hints

In Rust, match is an expression, not a statement. The whole match { ... } evaluates to one value, and you can return it directly from a function — no return, no ; at the end:

fn answer(x: u8) -> u8 {
    match x {
        1 => 10,
        2 => 20,
        _ => 0,
    }
}

Byte literals are written b'A' (a single ASCII byte as u8). To catch every value not listed explicitly, use a name binding pattern — the pattern other matches anything and binds the matched value to the name other:

match base {
    b'A' => b'T',
    // ... other arms ...
    other => panic!("complement_base: unsupported base {:?}", other as char),
}

You could also use _ as the catch-all, but binding to a name lets you include the offending byte in the error message.

Use the panic! macro. It takes the same format string as println!. For today, panicking is the right way to express “this input violates the function’s contract”; on day 3 we will return a Result instead, which gives the caller a chance to recover.

The {:?} formatter prints values using their Debug form — useful when the value might be non-printable. other as char re-interprets a byte as its character (see as cast expressions).

Solution

fn complement_base(base: u8) -> u8 {
    match base {
        b'A' => b'T',
        b'T' => b'A',
        b'C' => b'G',
        b'G' => b'C',
        b'a' => b't',
        b't' => b'a',
        b'c' => b'g',
        b'g' => b'c',
        b'N' => b'N',
        b'n' => b'n',
        other => panic!("complement_base: unsupported base {:?}", other as char),
    }
}

Full reference implementation lives in day1/ex-complement-solution/src/main.rs.

Where this leads

  • Day 2: lift this function to reverse_complement(seq: &[u8]) -> Vec<u8>, which reverses the sequence and complements each base. We will discuss whether to return a new Vec<u8> or write into a caller-provided buffer, and why both are useful.
  • Day 3: replace the panic with a Result so the caller can handle invalid input without crashing.