6
3

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.

Rustのstd::convertのFromとかIntoトレイトがわからなくなった時に見る記事

6
Last updated at Posted at 2021-06-03

この記事のモチベーション

Rustのstd::convertにはFromやInto、Asなどがありますが、トレイトがネストしてるときに何から何への変換なのかがわからなくなったので備忘録的にまとめてみました。

結論

FromとIntoはムーブする破壊的な変換、Asはムーブしない非破壊的な変換

実体の変換系

From<T>とInto<T>は逆の関係を持つ。

Fromトレイト

AがFrom<B>を実装していると、BからAへ向かって変換できる。例えば、StringはFrom<&str>を実装しているので、&strからStringへ変換できる。ムーブが発生する。

Intoトレイト

AがInto<B>を実装していると、AからBへ向かって変換できる。例えば、StringはInto<&str>を実装しているので、Stringから&strへ変換できる。ムーブが発生する。

参照の変換系

AsRefトレイト

AがAsRef<B>を実装していると、Aを&Bに変換できる。例えば、StringはAsRef<str>を実装しているので、Stringから&strへ変換できる。

AsMutトレイト

AがAsMut<B>を実装していると、Aを&mut Bに変換できる。例えば、StringはAsMut<str>を実装しているので、Stringから&strへ変換できる。

ここで注意したいのは

  • String
  • &String
  • &&String

のどれでもStringに対してas_mut()またはas_ref()したのと同じになる。つまり、

fn main() {
    let x:String = "hoge".to_string();
    let _:&str = x.as_ref();
    let _:&str = &x.as_ref();
    let _:&str = &&x.as_ref();
}

である。

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?