Skip to content

Instantly share code, notes, and snippets.

@pthariensflame
Last active October 28, 2016 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pthariensflame/f151f108851fbc9527efea7508695402 to your computer and use it in GitHub Desktop.
Save pthariensflame/f151f108851fbc9527efea7508695402 to your computer and use it in GitHub Desktop.

Rust’s Standard Conversion Traits

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:

The most basic conversion traits in the Rust standard library live in the std::convert module, and are named From and Into.

Go back to top.

Go back to top.

Go back to top.

Go back to top.

Go back to top.

Go back to top.

Go back to top.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment