liveBook · Manning

From trait

As explained in Learn Rust in a Month of Lunches

The From trait defines conversion of one Rust type into another specified type.

The From trait defines how one type becomes another. Choose a source type and a destination type, then provide the conversion in an implementation. Rust’s standard library uses From widely, including conversions from &str and String into Vec<u8>. section 7.2

A From implementation connects two types with a familiar constructor-like call:

  • Vec::from([8, 9, 10]) creates a vector containing the array’s numbers. section 7.2
  • Vec::from("hello") and Vec::from(String::from("hello")) produce Vec<u8> values containing the string’s bytes. section 7.2
  • Implementing From<Vec<City>> for Country allows Country::from(vector_of_cities) to collect cities into a country. section 7.2

Converting cities into a country

Define Country with a Vec<City>, then implement From<Vec<City>> for Country. The implementation receives the cities and returns Country { cities }. Code can then create Helsinki and Turku, place them in a vector, and convert that vector into a Country before printing each city and its population. section 7.2

From<&'_ [T]>
From<&'_ mut [T]>
From<&'_ str>
From<&'a Vec<T>>
From<[T; N]>
From<BinaryHeap<T>>
From<String>>
From<Vec<T>>
From<VecDeque<T>>

Browse representative standard-library From implementations, including slices, strings, arrays, vectors, and collection types. section 7.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the conversion rule, standard-library examples, custom implementations, blanket relationships, and the orphan-rule boundary.
Examples
Demonstrates array, string, byte-vector, City, Country, BTreeMap, and error conversions.
What it assumes
Assumes some exposure to Rust traits and structs while introducing conversion syntax through small examples.
What you can do after
Build it from scratch by implementing conversions for custom types and invoking them with From::from or Into.
How it connects
Connects From with traits, Into, TryFrom, blanket implementations, AsRef, and the orphan rule.

Also explained in

Compare how 4 books explain From trait →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.