Skip to content

Lesson 2 of 9 · 26m

Borrowing Across API Boundaries Without Contorting the Design

Design function signatures that express whether data is observed, mutated, consumed, or stored — and know when owned types are the honest boundary.

Bad Rust APIs often fail before the first implementation line: the signature lies. It borrows data that needs to live independently, consumes data that callers must reuse, or returns a reference tied to a temporary internal buffer. A senior Rust engineer treats signatures as contracts about time, ownership, and mutation — not merely as ways to pass values.

Choose the parameter shape deliberately

The usual decision table is simple:

&T        inspect without mutation
&mut T    mutate exclusively
T         consume or take ownership
Cow<'_, T> borrow usually, own only when needed
Arc<T>    shared ownership across tasks or threads

A parser that only inspects input should take &[u8] or &str. A decoder that appends into a buffer should take &mut Vec<u8>. A worker that must retain input after the caller returns should take an owned Vec<u8> or Arc<[u8]>. Do not smuggle lifetime requirements into a type because the first prototype happened to be single-threaded.

Do not let implementation details leak into lifetimes

This innocent function creates a constraint callers may not deserve:

fn first_line<'a>(input: &'a str) -> &'a str {
    input.lines().next().unwrap_or("")
}

That is fine because the returned slice really does borrow from input. But if the function later normalizes or allocates, the honest signature changes:

fn normalized_host(input: &str) -> String {
    input.trim().trim_end_matches('.').to_ascii_lowercase()
}

The mistake is forcing the new implementation back into the old borrowed contract. Let implementation needs reshape the API before users depend on it.

Borrowed input, owned output is a common sweet spot

Systems code often transforms untrusted input into normalized data. Borrow input for efficiency, return owned output for safety:

pub struct Endpoint {
    pub host: String,
    pub port: u16,
}

pub fn parse_endpoint(raw: &str) -> Result<Endpoint, ParseEndpointError> {
    let (host, port) = raw.rsplit_once(':').ok_or(ParseEndpointError::MissingPort)?;
    Ok(Endpoint {
        host: host.trim().to_ascii_lowercase(),
        port: port.parse().map_err(|_| ParseEndpointError::InvalidPort)?,
    })
}

The caller can drop raw immediately. Endpoint is independent, easy to store, and easy to send across tasks.

Beware "temporary convenience" structs

A struct that stores &str infects every user with a lifetime. Sometimes that is exactly right for zero-copy parsing. Often it is premature optimization. If values escape loops, tasks, cache entries, or error paths, owned fields are usually cheaper than the engineering time spent threading lifetimes.

Field notes

  • If callers routinely clone before calling your API, your signature may demand ownership it does not need.
  • If every caller wraps results in Arc, consider accepting or returning Arc explicitly instead of pretending ownership is local.
  • &mut means exclusive access for the duration of the borrow; do not use it merely because mutation is possible.
  • Public borrowed types are a commitment. Changing them later is a breaking API change, not an implementation detail.

Was this lesson helpful?

Sign in to rate