As_ref in Rust lang

What exactly is as_ref means ?. Can anyone please illustrate with a simple example ?.


Thanks Sir... but could it be simpler explanation ?.

As the documentation for the AsRef trait says:

Used to do a cheap reference-to-reference conversion.

Which means it allows you to get a reference to another type from a reference implementing this trait.

The most prominent example I can think of is AsRef<str>. Implementing AsRef<str> for a type T means that you can do this:

struct MyType(String);

impl AsRef<str> for MyType {
    fn as_ref(&self) -> &str {

fn greet(msg: &str) { println!("Hello, {}!", msg); }

fn main() {
    let x = MyType(String::from("example"));

As said a cheap conversion of references.

If you look at the implementors of AsRef you will quickly understand that AsRef is often used to conveniently convert between similar types, e.g. String implements AsRef<Path> and Box<T> implements AsRef<T> which means you can take a reference to the inner type of a Box.

However, you should not mistake the trait AsRef with Option::as_ref() or Result::as_ref() as those methods do something different (on the doc page of AsRef you can see that neither Option nor Result implement the AsRef trait). But this is another topic.


In practice it's used mainly on option. When you have &Option<Foo>, you have a reference to an option that owns its content. .as_ref() changes it to Option<&Foo> - owning an option that doesn't own its content.
The difference is that you can't .unwrap() &Option<Foo>, because you don't own the option, so you can't destroy it. In the other case you do own the option, so you can destroy it.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.