std::convert::AsRef

Trait std::convert::AsRef

pub trait AsRef<T> where    T: ?Sized, {
    fn as_ref(&self) -> &T;
}

A cheap reference-to-reference conversion. Used to convert a value to a reference value within generic code.

AsRef is very similar to, but serves a slightly different purpose than, Borrow.

AsRef is to be used when wishing to convert to a reference of another type. Borrow is more related to the notion of taking the reference. It is useful when wishing to abstract over the type of reference (&T, &mut T) or allow both the referenced and owned type to be treated in the same manner.

The key difference between the two traits is the intention:

  • Use AsRef when goal is to simply convert into a reference
  • Use Borrow when goal is related to writing code that is agnostic to the type of borrow and if is reference or value

See the book for a more detailed comparison.

Note: this trait must not fail. If the conversion can fail, use a dedicated method which returns an Option<T> or a Result<T, E>.

Generic Implementations

  • AsRef auto-dereferences if the inner type is a reference or a mutable reference (e.g.: foo.as_ref() will work the same if foo has type &mut Foo or &&mut Foo)

Examples

Both String and &str implement AsRef<str>:

fn is_hello<T: AsRef<str>>(s: T) {
   assert_eq!("hello", s.as_ref());
}

let s = "hello";
is_hello(s);

let s = "hello".to_string();
is_hello(s);

Required Methods

Performs the conversion.

Implementors

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/convert/trait.AsRef.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部