Ownership in Practice · 16 min · free with an account

Owned or Borrowed?

Lesson preview · about 30%

Choose a return type that matches the data flow.

Core idea

Return a borrow when the result is a view into an input; return an owned value when new data is created or must escape independently.

Start with the idea

Return a borrow when the result is a view into an input; return an owned value when new data is created or must escape independently. The choice affects allocation and API flexibility.

The lifetime of the data behind a return value should determine its type. trimmed(input: &str) -> &str returns a view into existing bytes, so it can avoid allocation, but the caller cannot keep the result after the input is gone. label(input: &str) -> String creates uppercase text in a new owned buffer. The caller may keep that buffer independently of the input. Neither choice is universally better; each promises a different relationship.

Follow the example with a String created in an inner block.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery