Module std::borrowUnstable [-]  [+] [src]

A module for working with borrowed data.

The BorrowFrom traits

In general, there may be several ways to "borrow" a piece of data. The typical ways of borrowing a type T are &T (a shared borrow) and &mut T (a mutable borrow). But types like Vec<T> provide additional kinds of borrows: the borrowed slices &[T] and &mut [T].

When writing generic code, it is often desirable to abstract over all ways of borrowing data from a given type. That is the role of the BorrowFrom trait: if T: BorrowFrom<U>, then &T can be borrowed from &U. A given type can be borrowed as multiple different types. In particular, Vec<T>: BorrowFrom<Vec<T>> and [T]: BorrowFrom<Vec<T>>.

The ToOwned trait

Some types make it possible to go from borrowed to owned, usually by implementing the Clone trait. But Clone works only for going from &T to T. The ToOwned trait generalizes Clone to construct owned data from any borrow of a given type.

The Cow (clone-on-write) type

The type Cow is a smart pointer providing clone-on-write functionality: it can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. The type is designed to work with general borrowed data via the BorrowFrom trait.

Cow implements both Deref and DerefMut, which means that you can call methods directly on the data it encloses. The first time a mutable reference is required, the data will be cloned (via to_owned) if it is not already owned.

Enums

Cow

A clone-on-write smart pointer.

Traits

BorrowFrom

A trait for borrowing data.

BorrowFromMut

A trait for mutably borrowing data.

ToOwned

A generalization of Clone to borrowed data.