-
-
Save hoangpq/5cd8ba41414f6fe8574394469b790a5e to your computer and use it in GitHub Desktop.
Rust: Borrow vs AsRef
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(non_snake_case)] | |
#![allow(dead_code)] | |
use std::borrow::Borrow; | |
use std::convert::AsRef; | |
struct Y; | |
struct X { | |
y: Y | |
} | |
impl X { | |
fn new() -> Self { | |
X { | |
y: Y | |
} | |
} | |
} | |
impl AsRef< Y > for X { | |
fn as_ref( &self ) -> &Y { | |
&self.y | |
} | |
} | |
impl Borrow< Y > for X { | |
fn borrow( &self ) -> &Y { | |
&self.y | |
} | |
} | |
fn as_ref_Y< T: AsRef< Y > >( _: T ) {} | |
fn borrow_Y< T: Borrow< Y > >( _: T ) {} | |
fn as_ref_X< T: AsRef< X > >( _: T ) {} | |
fn borrow_X< T: Borrow< X > >( _: T ) {} | |
impl AsRef< X > for X { | |
fn as_ref( &self ) -> &X { | |
self | |
} | |
} | |
fn main() { | |
as_ref_Y( X::new() ); | |
as_ref_Y( &X::new() ); | |
borrow_Y( X::new() ); | |
// borrow_Y( &X::new() ); // the trait `std::borrow::Borrow<Y>` is not implemented for `&X` | |
as_ref_X( X::new() ); // without `impl AsRef< X > for X`: the trait `std::convert::AsRef<X>` is not implemented for `X` | |
as_ref_X( &X::new() ); // without `impl AsRef< X > for X`: the trait `std::convert::AsRef<X>` is not implemented for `X` | |
borrow_X( X::new() ); | |
borrow_X( &X::new() ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment