概述

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()这样直接调用一样

定义

  1. pub trait AsRef<T> where
  2. T: ?Sized, {
  3. pub fn as_ref(&self) -> &Tⓘ;
  4. }

使用

因为需要显式的完成类型转换,因此常被用在**trait bound**上,对参数类型限制,目的有:

  • 为函数提供定义声明:即只接收能转换为**&T**类型的变量
  • 在函数内部会调用**x.as_ref()**类型转换

例子:把&strString做为类型参数传入,这两个类型实现了AsRef<str>,因此可以正常运行

  1. // 函数的trait bound指出:类型T要实现AsRef<str>
  2. // 即可以被转换为&str类型
  3. fn is_hello<T: AsRef<str>>(s: T) {
  4. assert_eq!("hello", s.as_ref());
  5. }
  6. #[test]
  7. fn main(){
  8. // 参数为&str类型
  9. let s = "hello";
  10. is_hello(s);
  11. // 参数为String类型
  12. let s = "hello".to_string();
  13. is_hello(s);
  14. }