BorrowCheck › Rust language core

Type conversions

From / Into, TryFrom, as casts, deref coercion, AsRef / Borrow, transmute.

The topic explains type conversions: explicit ones through the From, Into and TryFrom traits and the as operator, implicit ones through coercion, and unsafe ones through transmute. The questions check why implementing From gives Into but not the other way round, when the compiler lacks a target type for into(), and how the orphan rule forbids From between foreign types. The subtopic on as casts covers truncation and sign extension of integers, saturation when converting a float to an integer, the precision lost by u64 in f64, and which types do not cast to char. A separate part covers deref coercion: chains through Deref, coercion sites, why coercion does not apply to a parameter bounded by a trait, and why &Vec<String> does not become &[&str]. The subtopic on AsRef, Borrow and ToOwned explains why a HashMap<String, _> can be looked up by &str, which type Cow::Owned holds, and why clone() on a &str does not yield a String. The last subtopic is about transmute: the size check, byte order, an unbounded lifetime, and the undefined behavior of turning a &T into a &mut T.

38 questions: 16 basic, 20 intermediate, 2 advanced. 5 info pages, 31 sources.

Subtopics

  1. From / Into, TryFrom / TryInto
  2. as casts
  3. Deref coercion
  4. AsRef, Borrow, ToOwned
  5. transmute and its hazards

Previous: Closures · Next: Error handling