It’s often the case, when programming in Rust, that one needs to convert a value of one type to a corresponding value of another type. Some typical examples include:
- borrowing a vector as a slice;
- converting a Rust-style string to a C-style string;
- embedding an existing value in an
Option
; - getting an iterator from a collection;
- rendering a value of a structured type as a string;
- parsing a string as a value of a structured type; and
- converting a
Result
that uses a specialized error type to one that uses a more general error type.
To help solve this kind of problem, Rust has a plethora of standard conversion traits: traits in the standard library whose purpose is to generically convert between different types. Some of them are more commonly used than others, but all are present in the standard library for good (or at least decent) reason. The purpose of this document is to explore and educate about these traits: what they’re for, when to use them, and why the standard library includes them.
The following traits are covered:
std::convert::AsMut
std::convert::AsRef
std::borrow::Borrow
std::borrow::BorrowMut
std::ops::Deref
std::ops::DerefMut
std::convert::From
std::iter::FromIterator
std::str::FromStr
std::convert::Into
std::iter::IntoIterator
std::borrow::ToOwned
std::string::ToString
std::convert::TryFrom
std::convert::TryInto
The most basic conversion traits in the Rust standard library live in the std::convert
module, and are named From
and Into
.