1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AsRef & AsMut

Last updated at Posted at 2020-02-06

用途

std::convert::AsRefstd::convert::AsMut 用于非常方便且低成本的将类型(types)转换为引用(references)。

比如有类型 AB ,则

impl AsRef<B> for A

表示 &A 可以转换为 &B

同样:

impl AsMut<B> for A

表示 &mut A 可以转换为 &mut B`。

这种方式可以在类型转换的时候,避免值的拷贝和移动。比如标准库里的 std::fs::File.open() 方法定义如下:

fn open<P: AsRef<Path>>(path: P) -> Result<File>

这种定义方式,File.open() 除了可以接收 Path 类型的参数,还可以接收 OsStrOsStringstrString 以及 PathBuf 等类型的参数,因为这些类型都实现了 AsRef<Path>, 都可以隐式转换为 Path 类型。

实现

std::convert::AsRef 是一个 Trait

比如 为String类型实现AsRef<Path> 的代码如下:

impl AsRef<Path> for String {
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
}

看起来很简单。

VS From Trait

AsRef 是引用到引用(reference-to-reference)的转换,因此成本低。与此相对, From 是值到值(value-to-value)的转换,因此成本会比较高。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?