LoginSignup
27
9

More than 5 years have passed since last update.

AsRefトレイトについて

Last updated at Posted at 2019-03-03

例えば新規ファイルを作成する関数は&str&Pathも引数にとることができる。

std::fs::File::create("/var/tmp/hoge");
std::fs::File::create(&std::path::Path("/var/tmp/fuga"));

何故ならこの関数の引数の型は&strでも&Pathでもなく、AsRef<Path>を実装するような型Pであり、

fs.rs
fn create<P: AsRef<Path>>(path: P) -> io::Result<File>

pathモジュールでstrPathに対してAsRef<Path>が実装されているので、

path.rs
impl AsRef<Path> for Path {
    fn as_ref(&self) -> &Path {
        self
    }
}

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

as_refメソッドで&Pathを取り出すことができる。

fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
    let p: &Path = path.as_ref();
    ...
}
27
9
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
27
9