As asked
You are designing a Rust library API that accepts user data, transforms it, and returns a result. When would you take ownership, borrow immutably, borrow mutably, or accept Cow?
Sample answer outline
A strong answer starts from the caller contract, not from syntax. Borrow immutably when the function only needs to read data and should not force allocation or transfer of lifetime responsibility. Borrow mutably when the function must update caller-owned state and exclusive access is part of the API contract. Take ownership when the callee must store, move across threads, or consume the value. Cow is useful when most calls can borrow but a minority need normalisation or copying. Candidates often trip by cloning to satisfy the compiler instead of redesigning ownership so the data flow is explicit.
Reference implementation (rust)
use std::borrow::Cow;
fn normalise_name(input: Cow<'_, str>) -> Cow<'_, str> {
if input.chars().any(|c| c.is_uppercase()) {
Cow::Owned(input.to_lowercase())
} else {
input
}
}Expect these follow-ups
- How would your choice change if the value is stored in a background worker?
- When is Clone an acceptable API requirement?
- How do lifetimes appear in the public signature and what does that communicate?