convert

From and Into, TryFrom and TryInto, and AsRef and AsMut for cheap reference conversions.

主题页正文目前为英文。

The convert module defines traits for value and reference conversions. They are standard-library traits, not a third-party crate. Implementing From<T> for U also gives you Into<U> for T; official guidance is to implement From and let Into be provided. TryFrom and TryInto follow the same pattern for conversions that can fail and return Result.

AsRef<T> and AsMut<T> are cheap reference-to-reference conversions, such as String as &str or PathBuf as &Path. They are not the same as Borrow, which HashMap uses for key lookup and which is documented on the HashMap page. FromStr is the trait behind str::parse and is already used on the Option and Result page; this page does not repeat that recipe.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
From::from, Into::into, TryFrom::try_from, TryInto::try_intoConvert a value infallibly with From or Into, or fallibly with TryFrom or TryInto.
AsRef::as_ref, AsMut::as_mutAccept owned or borrowed values through a cheap reference conversion, or mutate through AsMut.

From, Into, TryFrom, and TryInto

From is an infallible conversion. u16 implements Into<u32> because u32 implements From<u16>, so both u32::from(7u16) and 7u16.into() work. TryFrom is for conversions that may fail. u16::try_from(80u32) succeeds; u16::try_from(70_000u32) returns Err with a TryFromIntError whose Display, checked on rustc 1.90.0, is "out of range integral type conversion attempted". try_into is the same conversion from the value side.

From::from, Into::into, TryFrom::try_from, TryInto::try_into

pub trait From<T>: Sized {
    fn from(value: T) -> Self;
}
pub trait Into<T>: Sized {
    fn into(self) -> T;
}
pub trait TryFrom<T>: Sized {
    type Error;
    fn try_from(value: T) -> Result<Self, Self::Error>;
}
pub trait TryInto<T>: Sized {
    type Error;
    fn try_into(self) -> Result<T, Self::Error>;
}

Convert a value infallibly with From or Into, or fallibly with TryFrom or TryInto.

ParameterDescription
value / selfThe value being converted. From and TryFrom are written on the target type; Into and TryInto are methods on the source value.

Returns: From and Into return the target type. TryFrom and TryInto return Result, with an associated Error type such as std::num::TryFromIntError for integer range checks.

Errors and panics

  • TryFromIntError — Returned when an integer cannot be represented in the target type. The Display text above was checked on rustc 1.90.0 and is a standard-library message, not an OS string.
  • There is a blanket From<T> for T, the identity conversion. Avoid writing a conflicting reflexive From impl.
  • PathBuf implements From<String> and From<&str>, which is a way to go from an owned string to an owned path.
rust
use std::convert::TryInto;
use std::path::PathBuf;

fn main() {
    let n: u32 = u32::from(7u16);
    let n2: u32 = 7u16.into();
    println!("from-into {n} {n2}");
    match u16::try_from(80u32) {
        Ok(v) => println!("try_from ok {v}"),
        Err(e) => println!("try_from err {e}"),
    }
    match u16::try_from(70_000u32) {
        Ok(v) => println!("try_from ok {v}"),
        Err(e) => println!("try_from err {e}"),
    }
    let via_into: Result<u16, _> = 80u32.try_into();
    println!("try_into {via_into:?}");
    let buf = PathBuf::from(String::from("tmp/foo"));
    println!("pathbuf-from {}", buf.display());
}

Expected output

from-into 7 7
try_from ok 80
try_from err out of range integral type conversion attempted
try_into Ok(80)
pathbuf-from tmp/foo

Related: Option and Result page, Path and PathBuf

Official documentation →

AsRef and AsMut

AsRef<T> lets a function accept either an owned value or a reference when it only needs &T. String and &str both implement AsRef<str>, so a helper can take either. AsMut<T> is the mutable counterpart; a function can take a &mut [i32] or another type that exposes one, and then write through as_mut(). These traits do not allocate, and they do not take ownership of the original value.

AsRef::as_ref, AsMut::as_mut

pub trait AsRef<T: ?Sized> {
    fn as_ref(&self) -> &T;
}
pub trait AsMut<T: ?Sized> {
    fn as_mut(&mut self) -> &mut T;
}

Accept owned or borrowed values through a cheap reference conversion, or mutate through AsMut.

ParameterDescription
selfas_ref borrows self and returns &T. as_mut borrows self mutably and returns &mut T.

Returns: A shared or mutable reference to T. The lifetime is tied to the borrow of self.

  • Path, PathBuf, and str implement AsRef<Path>, which is why fs functions and Path::join accept several path-like types.
  • AsRef is not used for HashMap key lookup; that is Borrow, documented on the HashMap page.
rust
fn takes_str<S: AsRef<str>>(s: S) -> usize {
    s.as_ref().len()
}

fn add_one(v: &mut impl AsMut<[i32]>) {
    v.as_mut()[0] += 1;
}

fn main() {
    println!("asref-str {} {}", takes_str("hi"), takes_str(String::from("hi")));
    let mut a = [1, 2];
    add_one(&mut a);
    println!("asmut {a:?}");
}

Expected output

asref-str 2 2
asmut [2, 2]

Related: HashMap and Borrow, Path and PathBuf

Official documentation →