Rust Lifetime Interview Exercises: Fixing Borrow Errors Without Unnecessary Clones
Quick Overview
Fix three Rust borrow checker failures in a log parser and explain which owner each reference depends on. Includes runnable repairs and interview follow-ups.
When Rust rejects a returned reference, start by finding the value that owns the bytes. Then check whether the function signature gives the caller enough information to keep that owner alive. A borrowed field can often be returned directly from its input. A field assembled in local scratch storage needs a different contract. An iterator may borrow its source only until its last use, or longer if you keep one of the references it yields.
The exercises below follow a log parser through those three situations. The PracHub string ownership exercise is a useful warm-up. Identify who owns the storage, then explain what happens when you move the owner versus copying its contents. The language rules here come from the Rust documentation. The parser and follow-up cases are original practice.

Start with a caller the parser should accept
You receive log lines such as "svc:ready". A setting tells the parser which prefix to strip. The function should return a borrowed suffix of the line. Callers can discard the setting as soon as parsing finishes, because the suffix comes from the line.
Here is a plausible signature that misstates the contract. It compiles as a function, but the caller below fails with E0597.
fn payload<'a>(line: &'a str, prefix: &'a str) -> Option<&'a str> {
line.strip_prefix(prefix)
}
fn main() {
let line = String::from("svc:ready");
let result;
{
let prefix = String::from("svc:");
result = payload(&line, &prefix);
}
assert_eq!(result, Some("ready"));
}
Look at the scopes in the caller. line lives past the assertion. prefix is dropped at the end of the inner block. By using the same lifetime parameter for both inputs and the output, the public signature requires a common lifetime for both input borrows and the output. The caller needs to use the result after the prefix has gone away, so it cannot pick a lifetime that satisfies the signature. The two owners can have different scopes. The problem is that the signature couples the borrows at the point of use.
This is a good place to explain the difference between a function body and an API. The implementation calls strip_prefix and can see that the slice comes from line. The caller can rely on the function's declared type. It cannot rely on inspecting today's implementation, which might later return a reference into the other input. The compiler is enforcing the relationship we wrote, even though the implementation happens to use a narrower relationship.
Give the returned slice a lifetime tied only to the source of its bytes.
fn payload<'line>(line: &'line str, prefix: &str) -> Option<&'line str> {
line.strip_prefix(prefix)
}
fn main() {
let line = String::from("svc:ready");
let result;
{
let prefix = String::from("svc:");
result = payload(&line, &prefix);
}
assert_eq!(result, Some("ready"));
assert_eq!(payload(&line, "job:"), None);
assert_eq!(payload("svc:", "svc:"), Some(""));
}
The prefix still has to be valid during the call. It imposes no lifetime constraint on the return value. The three assertions also distinguish a missing prefix from a matched prefix with an empty suffix. Returning an empty string for both would change the parser's observable behavior.

Change the signature when the fallback changes the owner
Suppose the interviewer now asks for a default value supplied by the caller. On a match, return a slice of the line. On a miss, return the supplied default. You just introduced another possible owner for the output.
fn payload_or<'a>(line: &'a str, fallback: &'a str) -> &'a str {
line.strip_prefix("svc:").unwrap_or(fallback)
}
A shared lifetime is appropriate here. A single returned reference could be backed by either input. If the fallback is dropped before the caller reads the result, a caller with a matching line might still be rejected. The signature has to permit the miss branch, and a lifetime annotation cannot make its result conditional on the string's contents. Test the hit and the miss before arguing that the stricter signature is unnecessary.
There is another design if the caller needs a longer borrow on the success path. Return Option<&str> tied to the input and let the caller decide what to do on a miss. For example, a handler can send borrowed successes immediately and turn misses into an error counter. This keeps the fallback decision at a point where the caller knows the branch. If downstream code must retain both cases independently of the two inputs, return an owned value or ask the caller to provide the storage for the output. Each design answers a different question about who keeps the bytes alive.
| Return contract | Source of bytes | Caller consequence |
|---|---|---|
| Borrowed suffix with separate prefix borrow | Input line | A short-lived prefix is fine. Keep the line alive through the last use. |
| Borrowed suffix or caller's fallback | Line or fallback | Both inputs must support the caller's use of the result. |
| Owned normalized record | Returned string | Caller can drop the source and retain the record. Decide where the copy happens. |
This is also how to answer a follow-up about elision. With only one borrowed input, Rust can often infer which lifetime an elided output borrows. With two borrowed inputs in a free function, make the relationship explicit when the output is borrowed. A method has an additional receiver rule. If a method returns a slice from a separate input, read the signature carefully before assuming an elided output refers to that input.
Trace the iterator and the item separately
The parser next needs to count words in a buffer and append a status marker. split_whitespace() produces slices of the existing string. The iterator needs access to that string while it is in use. A slice obtained from the iterator can keep the borrow relevant after the iterator has been consumed or dropped.
The following code deliberately fails with E0502. The println! uses the slice after the attempted mutation.
fn main() {
let mut line = String::from("svc ready");
let first = line.split_whitespace().next().unwrap();
line.push_str(" ok");
println!("{first}");
}
The temporary iterator has already finished its part of the work by the time push_str is called. The item is still a reference to the old buffer. Rust cannot allow a mutable borrow of that buffer while the slice is live. A growing string could also move its bytes. Preallocating spare capacity would leave the aliasing conflict intact. The rule protects the access pattern even if this particular push would fit.
For a count, consume the iterator and keep the resulting integer. For a label you only need to display, use the slice before appending. The following version shows both, followed by a mutation and an assertion on the new value.
fn main() {
let mut line = String::from("svc ready");
let count = line.split_whitespace().count();
let first = line.split_whitespace().next().unwrap();
assert_eq!(first, "svc");
line.push_str(" ok");
assert_eq!(count, 2);
assert_eq!(line, "svc ready ok");
}
| What crosses the mutation? | Expected result | How to defend it |
|---|---|---|
| Count only | Compiles | The integer is a value. The iterator was consumed. |
| First slice, last used before the push | Compiles | The last use ends the relevant shared borrow before mutation. |
| First slice, used after the push | E0502 | The slice still needs the string while the push needs mutable access. |
| First token copied into its own string | Compiles | The retained token now has separate storage. This is a deliberate ownership decision. |
If the requirements insist on the old first token surviving arbitrary edits, a separate owned token is a reasonable repair. An index or range is another option only if later reads are defined against a stable version of the buffer. An insertion or normalization can change which bytes the range describes. Byte offsets also need to be valid UTF-8 boundaries when used to slice a str. Explain the edit and revalidation policy before suggesting that an index preserves the original token.
Return the owner when the bytes are built locally
Now suppose the log collector wants a normalized record in a queue that can outlive the parser call. A tempting attempt is to build an uppercase string and return its view.
fn normalize<'a>(raw: &'a str) -> &'a str {
let scratch = raw.trim().to_ascii_uppercase();
scratch.as_str()
}
fn main() {
let _ = normalize(" ready ");
}
This fails with E0515. scratch owns the normalized bytes and is dropped when the function returns. The input lifetime says how long raw may be borrowed. It says nothing about a string allocated inside the function. Moving the owner out is enough here.
fn normalize(raw: &str) -> String {
raw.trim().to_ascii_uppercase()
}
fn main() {
let mut queue = Vec::new();
{
let raw = String::from(" ready ");
queue.push(normalize(&raw));
}
assert_eq!(queue[0], "READY");
}
The uppercase conversion produces the owned output. Returning that String transfers ownership to the caller without adding a clone of the finished result. The queue holds it after raw is dropped. In an interview, say whether you need ASCII normalization or Unicode-aware behavior. This example deliberately uses ASCII case conversion. If no transformation is needed and the data stays within the source's lifetime, a borrowed trim() result may suffice. If the API needs both a borrowed fast path and an owned changed value, Cow<'_, str> can express the two outcomes. A queue that can outlive the source still needs to make the borrowed case owned before accepting it.
The question to ask before picking a repair is whether the consumer wants a view of the original bytes, an independent snapshot, or a freshly transformed value. That answer often tells you which allocation is necessary. Benchmark the implementation on realistic input before making a performance claim. The examples were checked with rustc 1.98.1 in the 2021 edition. The three deliberate failures produce E0597, E0502, and E0515, and the passing examples run their assertions. These checks cover the snippets and their outputs. A performance claim would need a separate allocation or timing measurement.
Which cases deserve a regression test?
The most valuable test for the first repair is a caller whose configuration goes out of scope before the slice is read. A normal test that keeps both strings alive can pass with either signature, so it misses the regression. Keep a separate compile-fail witness where the input line goes out of scope too. That catches a later attempt to claim the parser can produce a reference independent of its input.
For the queue, assert after dropping the raw input and use a case that forces a transformation, such as a mixed-case suffix with surrounding spaces. A test of a string literal alone can hide the ownership boundary because the literal remains valid for the program's duration.
Rehearse the explanation with one change at a time
Take the corrected parser and move the line owner into the same block as the prefix. Predict the assertion's fate before you compile. It now fails because the result really does borrow the line. Then restore the line's scope and change the contract to return the borrowed fallback. Compare the failure with the first case. The diagnostic may again mention a short lifetime, but the reason has changed. This time the signature is telling the truth about both possible owners.
For the iterator, move println! before the push and rerun. Next make the old value available after an edit by intentionally giving the token its own storage. Say which data is retained, how long it survives, and whether the owned token must reflect later buffer changes. A repair that silently changes a view into a snapshot can be wrong for the caller even when the compiler accepts it.
These PracHub records are practice material rather than forecasts of an employer's exact interview. The first two focus on strings and ownership. The remaining exercises transfer the same reasoning to callback boundaries, buffering and shared owners.
| PracHub question | Follow-up to rehearse |
|---|---|
| Explain and Implement Strings | Identify the allocation and distinguish an owned string move from copying its bytes. |
| Explain strings and copy complexity | State the cost of duplicating a buffer and describe when a borrowed view suffices. |
| C++ Basics: const vs static, Non-Virtual Base Destructors, and Stack vs Heap Memory | Distinguish storage duration from the last valid use of a view. Keep the C++ and Rust guarantees separate. |
| Implement buffered file writer with concurrency support | Decide when the writer can borrow bytes and when a background queue must own them. |
| Define and compare smart pointers | Distinguish owning handles from borrowed access to the value. |
Open Explain and Implement Strings, then give two versions of your API. In one, the caller owns the backing string and takes a slice. In the other, a queue keeps the data after the source is gone. For each version, mark the owner, the last use, and the operation that moves or copies the bytes.
Comments (0)