概述
AsRef trait同样用于引用类型的转换,和Deref trait相比,它需要显式(explicit)的调用
与其对应的是**AsMut** trait,用来转换可变引用(mutable references)
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)
AsRef trait会自动解引用,对于&mut Foo或&&mut Foo类型的变量,效果和foo.as_ref()这样直接调用一样
定义
pub trait AsRef<T> whereT: ?Sized, {pub fn as_ref(&self) -> &Tⓘ;}
使用
因为需要显式的完成类型转换,因此常被用在**trait bound**上,对参数做类型限制,目的有:
- 为函数提供定义声明:即只接收能转换为
**&T**类型的变量 - 在函数内部会调用
**x.as_ref()**做类型转换
例子:把&str和String做为类型参数传入,这两个类型实现了AsRef<str>,因此可以正常运行
// 函数的trait bound指出:类型T要实现AsRef<str>// 即可以被转换为&str类型fn is_hello<T: AsRef<str>>(s: T) {assert_eq!("hello", s.as_ref());}#[test]fn main(){// 参数为&str类型let s = "hello";is_hello(s);// 参数为String类型let s = "hello".to_string();is_hello(s);}
