API Boundaries · 16 min · free lesson

Flexible Borrowed Inputs

Accept several string-like types when the operation only needs a borrowed view.

Core idea

Ask for ownership only when the operation needs to keep or consume the value.

Diagram for Flexible Borrowed Inputs: a Rust code example flows to the lesson rule and the key observation.
AsRef without unnecessary ownership

Understand it

A function that only inspects text does not need a String allocation from every caller. A borrowed &str is often the simplest signature. AsRef<str> is useful when an API intentionally accepts several owned or borrowed string-like types and immediately obtains a string slice from them. It is a cheap reference conversion, not a general parsing or validation mechanism.

The example accepts a generic input, calls as_ref(), trims surrounding whitespace, and returns the number of Unicode scalar values. It never stores a reference after the call returns. Taking T by value still moves an owned String passed directly; callers that want to keep it can pass a reference. Generic syntax does not repeal ownership rules.

Choose the narrowest useful contract. A public function taking &str is easy to read and accepts &String through coercion. An AsRef<Path> parameter can be convenient for a file adapter, but path conversion does not grant filesystem permission. Similarly, AsRef<str> does not prove a string is a valid URL, port, or record. Keep the validated domain constructor from the earlier lesson as a separate operation.

Local compiler profile: standard library only. The lab calls the same function with a string literal, a String, and a borrowed String. It includes accented text and an emoji so byte length cannot accidentally pass as character count. Rust chars are Unicode scalar values; they are not the same as user-perceived grapheme clusters, so describe the result precisely rather than calling it a universal display width.

Read the code

fn scalar_count(text: impl AsRef<str>) -> usize {
    text.as_ref().trim().chars().count()
}
fn main() {
    let owned = String::from(" É🦀 ");
    assert_eq!(scalar_count(&owned), 2);
    assert_eq!(owned, " É🦀 ");
}

AsRef without unnecessary ownership

Try it

Trim surrounding whitespace and count Unicode scalar values for any AsRef<str> input. This is not byte length or grapheme count. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

If an owned String is passed by value to fn f<T: AsRef<str>>(value: T), is the original still available?

Reveal the answer
  1. Always, because AsRef implies Copy
  2. No, unless it was borrowed or cloned before the call
  3. Only when the text is ASCII

AsRef supplies a borrowed view inside the function. Passing the owned argument by value still moves it.

Go deeper

Common misconception: AsRef means arguments can never be moved.

The conversion is borrowed, but the parameter's ownership mode still matters.

  1. Accept: Choose a borrowed slice or a justified generic input.
  2. View: Call as_ref only for the lifetime of the operation.
  3. Specify: Count scalar values, not bytes or grapheme clusters.

Transfer challenge: Compare a &str API and an impl AsRef<str> API at three call sites. Keep the simpler public contract unless flexibility has a concrete benefit.

Connections

  • Compose Optional Fallible Input: map, transpose, and explicit defaults