文字起こし · CC BY 4.0

Rustの核心: ディスパッチ、単相化、ファットポインタ — Jon Gjengset

このページのタイトル、字幕、要約、読書メモは保存済みの AI 翻訳です。誤りが含まれる場合があります。タイムスタンプは原文と同じです。原文の字幕を開き、元の動画と照合できます。

Jon GjengsetがRustにおける静的ディスパッチと動的ディスパッチを掘り下げ、ジェネリクス、単相化、vtable、トレイトオブジェクト、自動トレイト、Sized境界を扱う。

Jon Gjengset · 公開 · 2時間13分 · 英語 · ライセンス: CC BY 4.0 · 出典: YouTubeで視聴

文字起こしの出典:YouTubeの手動字幕。VidleafによるAI句読点付与。元の文言とタイムスタンプのアンカーは保持されています。元の文字起こしは以下でご覧いただけます。

AI生成の要約

このRustストリームでは、トレイト、静的ディスパッチと動的ディスパッチ、Sizedトレイト、ワイドポインタまたはファットポインタ、vtable、コヒーレンスといった半関連のトピック群を扱い、どれか一つの深みにはまりすぎずに、それらがどのように組み合わさるかを説明することを目指しています。時間を抑えるために一部の詳細は省略され、深掘りは後日になる可能性があります。Rust Bookのジェネリクスのパフォーマンスに関する節、特に単相化を分解します。単相化とは、コンパイル時に具体的な型を埋めることでジェネリックコードを特定のコードに変えることで、例えばAsRef<str>を実装する任意の型を受け取るジェネリックなstrlenが&'static strとStringで呼ばれたときにコンパイラが二つのコピーを生成する場合や、ジェネリックなHashMapが使用される型ごとにその構造体とメソッドのコピーをオンデマンドで生成する場合です。これにより、動的リンクライブラリのようにRustコードをライブラリとして出荷するのはやや難しくなります。なぜなら、消費側の型のインスタンスを生成するにはソースが必要だからです。利点としては、インライン化と最適化により潜在的にずっと効率的なコードが得られること、欠点としてはバイナリが大きくなること、命令キャッシュ効率がやや悪くなること、コンパイラコストがかかることがあります。静的ディスパッチは、strに対して実装されたカスタムトレイトを通して説明されます。そこでは具体的な型がコンパイル時に既知であるため、呼び出しは既知の場所へのアセンブリ呼び出しになります。動的ディスパッチは、複数のコピーが不要な場合、例えばトレイトを実装するもののベクタのような場合の代替手段です。その後、異なる型のベクタを作成できない理由、GUI描画の例、dynで示されるトレイトオブジェクト、すべてのトレイト境界によって暗黙に要求されるSizedマーカートレイト、型消去、データポインタとvtableポインタを保持するファットポインタ、オブジェクト安全性のルール、そしてCloneやExtendのようなトレイトがトレイトオブジェクトになれない理由について説明します。後のセグメントでは、動的サイズ型、トレイトオブジェクト、ディスパッチを扱います。DINトレイトは、メタデータがDINメタデータであるポインティトレイトになり、型のサイズ、アラインメント、ドロップと配置ポインタ、メソッドポインタを保持するvtableへのポインタになります。ポインティトレイトは同様に、参照なしのU8スライスに対しても実装でき、メタデータとしてUサイズの長さを持ちます。この機能はまだ新しく実験的であり、講演者はRFCを読むことを勧めています。RFCには、空のメタデータを持つポインティを実装する任意の型のためのトレイトエイリアスthinが含まれ、ポインタメタデータを内省するメソッドを提供し、決定的に重要なことに、実行時にオンザフライでvtableを構築できるようにします。これは標準ライブラリがasyncのwakerに対してすでに行っています。彼はfn、dyn fn、impl fnを対比し、U8スライスへの参照がどのように長さを格納するかについての不確実性を指摘し、構造体の最後のフィールドのみが動的サイズ型を持てることを説明します。聴衆からのdynのスライスVecのリクエストは、トレイトオブジェクト、vtable、Anyトレイトの話につながります。配列要素は同じサイズにする必要があり、異なるコンパイル単位が同じ型とトレイトに対して異なるvtableを生成する可能性があります。Anyは、コンパイラ固有の型識別子を返す関数を持つトレイトとして説明され、ダウンキャストを可能にするためにvtableに追加されます。セッションはおよそ2時間15分で感謝の言葉とともに終了します。

文字起こしから生成されました。リンクされた箇所は元の動画と照合してください。

タイムスタンプ付きの章の要約

トレイト、ディスパッチ、単相化

ストリームの範囲: トレイトとディスパッチのトピック

  • [0:28] このストリームでは、トレイト、動的ディスパッチと静的ディスパッチ、Sizedトレイト、ワイドポインタまたはファットポインタ、vtable、コヒーレンスといった、やや関連するトピック群を扱います。
  • [0:52] これらのトピックは、程度の差はあれ互いに関連しており、目標は、どれか一つの深みにはまりすぎずに、それらがどのように動作し、どのように組み合わさるのかを説明することです。
  • [1:13] ほとんどのトピックは実用的な詳細レベルで扱い、後のストリームで深掘りする可能性もあるため、時間を抑えるために一部の詳細は省略するかもしれません。

ジェネリクスのパフォーマンスに関するRust Book

  • [1:35] Rust Bookには、ジェネリック型、トレイト、ライフタイムに関する章があり、ジェネリクスを使ったコードのパフォーマンスに関する小节も含まれています。
  • [1:59] このストリームの目的は、その節の見かけ上の魔法、特に単相化という考え方を分解して説明することです。
  • [2:07] 単相化は、コンパイル時に使用される具体的な型を埋めることで、ジェネリックコードを特定のコードに変換するプロセスとして説明されています。

ジェネリックなstrlenの例

  • [3:17] ジェネリック関数strlenは、AsRef<str>を実装する任意のものを受け取り、as_ref().len()を介してusizeを返します。
  • [3:46] 同等の形式は、SがAsRef<str>を実装するSに対してジェネリックな関数であり、どちらもstrへの参照に変換可能な任意の型を受け入れるジェネリック関数です。
  • [4:36] 関数fooは、"hello world"(&'static str)とString::from("hello world")(String)でstrlenを呼び出し、二つの呼び出しが異なる型を渡していることを示しています。
  • [5:30] StringはAsRef<str>を実装しています。なぜなら、Stringへの参照からstrへの参照を簡単に得られるからです。Stringの内部表現はstrだからです。

ジェネリック呼び出しの単相化

  • [5:44] ジェネリクスが便利なのは、与えられた関数をより柔軟に、またはより人間工学的に呼び出せるようにするからです。
  • [5:56] 舞台裏では、コンパイラが使用される型ごとに関数のコピーを二つ生成しており、これがRust Bookの言う単相化です。
  • [6:10] コンパイル時に、これによりstrを受け取ってstr::lenを呼び出す&str用のstrlenと、Stringを受け取って同じことを行うString用のstrlenが生成されます。
  • [6:39] 一つのジェネリック定義がコンパイラによって複数の非ジェネリック実装に変換されることが、Rustにおけるジェネリクスの動作の鍵です。

Rustジェネリクスにおける単相化

ジェネリック型に対するオンデマンドのコード生成

  • [6:54] 単相化は関数だけでなく、型にも適用されます。
  • [6:59] 汎用のHashMapは、使用される型ごとに構造体とそのすべてのメソッドの完全なコピーを取得します。
  • [7:13] 一度も呼び出されなかった型に対してコピーは生成されません。生成はコンパイル時にオンデマンドで行われ、考えられるすべての型に対して行われるわけではありません。
  • [7:34] 特定のHashMap型インスタンスは、その型の組み合わせが実際にコードのどこかに現れる場合にのみ生成されます。

バイナリ配布とソースの必要性

  • [7:46] これは、Rustのコードをコンパイルして、動的リンクライブラリのようにライブラリとして使用できるバイナリを出荷するのがやや難しい理由の一つです。
  • [8:11] Rustの契約は、型ごとに関数の異なるコピーを生成することですが、利用側はソース関数が存在する場所で定義されていない型でそれをインスタンス化する可能性があります。
  • [8:26] したがって、それらすべてのインスタンスを生成するにはソースが必要です。

具体的なコードによるパフォーマンスの向上

  • [8:31] 単相化は、潜在的にずっと効率的なコードを生成できるため、素晴らしいものです。
  • [8:54] HashMapでは、各具体的なキー型が独自のコピーを取得するため、コンパイラはキー型ごとにハッシュ関数をインライン化できます。
  • [9:26] 文字列キーのHashMapバージョンでは、文字列ハッシュコードをHashMapのコードに直接組み込み、型が文字列であることに基づいて最適化できます。
  • [9:41] 数値キーの場合、ジェネリクスが単相化されるとコンパイラはハッシュを完全に省略するかもしれませんが、話者はそれは実際には真実ではないかもしれないと述べています。
  • [9:54] コンパイラは使用される特定の型に対して具体的に書き出されたコードを見ることができ、それによりずっと優れた最適化が可能になります。

バイナリの肥大化とメソッドの部分生成

  • [10:28] 単相化の欠点は、使用される型ごとに型または関数のコピーが生成されるため、バイナリが大きくなることです。
  • [10:45] 増加は型の数を掛けるほど悪くはありません。特定の型の組み合わせに対して実際に呼び出されたメソッドのみが生成されるため、コストが少し償却されます。
  • [11:14] それでも、単相化が最終バイナリのコードを増やすことは確かです。

命令キャッシュの効率とコンパイルコスト

  • [11:20] 副作用として、命令キャッシュの効率がわずかに悪化します。キャッシュに残せる一つの関数のマシンコードの代わりに、別々のメモリ領域にある二つの別個の関数を別々にキャッシュする必要があります。
  • [12:07] これらのコピーの生成にもコンパイラのコストが少しかかりますが、非常に多くの型がインスタンス化されない限り、通常はそれほど大きくありません。
  • [12:25] 話者は、CのバイナリよりもRustのバイナリが大きいのは少し異なると述べています。Rustのバイナリはより多くのものを静的にコンパイルするためです。

Rustのバイナリサイズ、単相化、ジェネリクス

Rustバイナリが大きくなる原因

  • [12:38] 単相化はバイナリが大きくなる理由の一つであり、標準ライブラリのコードがより多くコンパイルされる可能性があります。
  • [12:48] もう一つの大きな要因は、Rustがしばしばデバッグシンボルを組み込むことです。そのため、バイナリをストリップしてみる価値があるかもしれません。

ジェネリック関数の単相化とインライン化

  • [13:07] 単相化が役立つのは、bool_thenのようなジェネリック関数が、渡されたクロージャのコードを直接インライン化したコピーを生成できるからです。
  • [14:18] インライン化は保証されません。関数が特定の型に単相化されるため、コンパイラは型を把握しており、必要に応じてインライン化と最適化を選択できます。

標準ライブラリの使用とコード重複のコスト

  • [14:42] 実際に使用された標準ライブラリの部分だけがバイナリに含まれますが、標準ライブラリのジェネリクスを多用するとサイズが増大します。
  • [15:00] メソッドの重複はサイズ的にはほとんどコストがかかりませんが、関数の多くのコピーをマシンコードにコンパイルするとコンパイルが遅くなります。

参照と動的リンクの制限

  • [15:18] strlenのような関数は、文字列を値渡しでも参照渡しでも受け取れますが、参照渡しが&strが優れている理由の一つです。
  • [15:34] 動的ライブラリはジェネリクスを扱えないため、Rustライブラリの動的リンクやバイナリ配布が困難になります。Cスタイルの動的リンクライブラリの外部関数はジェネリックにできません。

Rustにおける静的ディスパッチと単相化

カスタムHelloトレイトの定義

  • [16:40] 話者は、Hello(またはノルウェー語の挨拶)と呼ばれるカスタムトレイトを定義します。これは、何も返さずノルウェー語で挨拶するだけの単一のメソッドを持ちます。
  • [17:10] このトレイトはstrに対して実装され、メソッドはselfを使って一行を出力します。

具体的なstr参照に対するメソッド解決

  • [17:46] str参照に対する呼び出しのコードを生成する際、コンパイラは型を決定し、その参照型で利用可能なメソッドを確認します。
  • [18:06] 参照型にhiというメソッドが見つからない場合、スコープ内のトレイトを調べ、レシーバ型に対して実装されたhiメソッドを見つけて呼び出します。

ジェネリック関数と単相化

  • [18:21] hiを実装する何かを受け取るジェネリック版では、コンパイラはHの型を知らないままメソッドを呼び出す必要があります。
  • [18:47] 単相化は、Hがstrに束縛されたbar_strのような具体的なバージョンを生成するため、具体的な型が判明します。

コンパイル時の静的ディスパッチ

  • [19:10] これが静的ディスパッチです。コンパイル時にコンパイラが実際の型を把握しているため、どのメソッドが呼ばれるかを知っています。
  • [19:22] 呼び出しはメモリ上の既知の位置にある関数へのアセンブリ呼び出しになり、特化されたメソッドが生成されればコンパイルは容易になります。

単相化の代替としての動的ディスパッチ

静的ディスパッチと impl Trait の糖衣構文

  • [19:50] 話者は、この方法はもう一方と実質的に同じであり、どちらも high メソッドがどこにあるかを容易に特定できると述べています。
  • [20:27] `impl Trait` はジェネリクスの単なる糖衣構文であり、ジェネリック形式 `H: High` と等価です。

動機:複数のコピーを避けること

  • [20:50] 単相化を望まない場合、つまり複数のコピーが生成されることを望まない場合に、この代替手段が必要になります。
  • [21:03] もう一つの動機は、High を実装するもののベクタを作り、各要素に対して `h.high` を呼び出したいということです。

単一の具体的な型のスライス

  • [21:29] ベクタを反復処理して `h.high` を呼び出すのは、すべての要素が同じ型であれば問題ありません。
  • [21:51] High を実装するもののスライスを受け取る関数 `bar` は動作し、単一の具体的な型で呼び出された場合には問題なくコンパイルされます。
  • [22:27] 各要素を文字列に変換するのも問題なく動作しますが、話者はこれを文字列用に実装していなかったと述べています。

異種コレクションの必要性

  • [22:58] そもそも異なる型のもののベクタを作ることはできません。
  • [23:08] この場合、具体的な型は重要ではなく、重要なのは要素が High トレイトを実装していることだけです。
  • [23:19] 話者は、具体的な型を気にせずにこの振る舞いを持つもののベクタを作れるべきだと主張しています。

動的ディスパッチとトレイトオブジェクト

異なる具体的な型を一つの型として扱う

  • [24:00] この本には、異なる具体的な型のものを同じ型として扱うことについてのまともな章があります。
  • [24:10] GUI の例:ボタン、画像、テキストボックスなど多くのものが draw トレイトを実装しており、draw 関数は描画可能なもののイテレータを必要とするだけです。
  • [24:39] これは、high のようなメソッドを呼び出せるものの一部を取り出したいという願望に似ています。

単一のジェネリック型パラメータが失敗する理由

  • [24:48] 必要とされるものはトレイトオブジェクトと呼ばれ、dyn キーワードで示されます。
  • [25:05] impl の省略形を書き出すと、Bar が一つの型に対してジェネリックであり、その型は str 参照か String のどちらかでなければならず、両方ではないことがわかります。
  • [25:28] スライスやイテレータでは、イテレータの要素が一つの型しか持たないため、二つ目の型パラメータを置く場所がありません。

dyn とサイズ不定値によるコンパイラエラー

  • [25:55] 裸のトレイト型を書くと、明示的な dyn のないトレイトオブジェクトは非推奨であるというコンパイラエラーが発生するため、dyn が追加されます。
  • [26:16] 次のエラーは、dyn high 型の値のサイズはコンパイル時に知ることができず、Sized トレイトが dyn high に対して実装されていないというものです。
  • [26:29] スライスと配列の要素はサイズ付きの型でなければならず、話者はこのエラーを、Sized の意味と、それが動的ディスパッチやトレイトオブジェクトとどう結びつくかとともに説明する予定です。

意図された目標としての型消去

  • [27:14] 目標は型消去と考えることができます。つまり、トレイトを実装しているということだけを気にして、もののコレクションを扱うこと、すなわちトレイトの抽象的な概念です。
  • [27:35] コンパイラの課題はまさにこのケースであり、話者はそれが理にかなっているか確認するために一旦止まります。

Rust の Sized トレイトがジェネリック型にとって重要な理由

暗黙の境界を持つマーカートレイトとしての Sized

  • [27:54] Sized トレイトにはメソッドがなく、marker モジュールで定義されたマーカートレイトであり、コンパイル時にサイズが既知の定数サイズを持つ型として説明されています。
  • [28:07] Foo のような構造体やほとんどの標準ライブラリの型を含むほとんどの型はサイズ付きであり、サイズなしの型はごくわずかです。
  • [28:21] すべてのトレイト境界は、単なる Foo<T> であっても、その型が Sized であることを要求する暗黙の境界を伴います。

コンパイラはコード生成のために引数のサイズを知る必要がある

  • [29:05] *str を実装する S に対するジェネリックな strlen は、S を受け取り、参照の長さを介して usize を返します。
  • [29:34] 引数はスタック空間を占めるか、レジスタで渡される必要があるため、コンパイラは生成されるアセンブリで空間を割り当てるためにその大きさを知る必要があります。
  • [30:23] String の実装では、コンパイラは引数が三つのワード(長さ、割り当てサイズ、ヒープポインタ)であることを知っているため、アセンブリを簡単に生成できます。
  • [31:02] 同様に、戻り値の型に対してジェネリックであることは、そのためにどれだけのスタック空間を割り当てるかを知る必要があります。

dyn Traitがサイズ不定でスライスを壊す理由

  • [31:44] dyn Hiは、具体的な値を持たずにHiを実装するあらゆるものを意味します。スライスにはString、str、あるいはサイズの異なる他の実装者が格納される可能性があるからです。
  • [32:03] Stringは二つの数値とポインタ、strは一つの数値とポインタであり、仮想的なFooはギガバイト級の大きさになり得るため、スライスには単一の要素サイズが存在しません。
  • [32:28] スライスは各チャンクが同じサイズである連続したメモリなので、要素のサイズが不明であれば、同じサイズの要素を保証することはできません。
  • [32:52] 四番目の要素へのポインタ演算(開始位置に要素サイズの三倍を加算)は、要素のサイズが異なる場合には生成できません。これが、スライスと配列の要素がサイズ付きの型でなければならない理由です。

サイズ不定のコレクション問題の修正

  • [33:24] 話し手は、トレイトを実装するものをコレクションとして扱う能力を維持したいと考えています。Rustにそれが欠けていたらおかしいからです。
  • [33:45] dyn AsRef<str>を受け取るstrlen2は、スライスの例と同じ問題を抱えています。

RustのSizedトレイトとサイズ不定型

サイズ不定の引数に対するコンパイラエラー

  • [33:57] この例をコンパイルすると、dyn AsRef str型の値のサイズはコンパイル時に知ることができず、Sizedはdyn AsRefに対して実装されていないというエラーが発生します。
  • [34:17] コンパイラは関数の引数が静的に既知のサイズを持つことを要求しますが、借用型は常に既知のサイズを持ちます。
  • [34:26] コンパイラは関数呼び出しのコードを生成するために引数の型のサイズを知る必要があり、そのためサイズ付きの型は基本的な要件となります。

Sizedの自動実装

  • [34:59] Sizedは実装可能なあらゆる型に対して自動的に実装されるため、フィールドを持たない構造体や、Stringやboolを保持する構造体はサイズ付きです。
  • [35:27] ジェネリックな構造体foo<T>は、すべてのトレイト境界が暗黙のT: Sized要件を伴うため、すべてのフィールドがサイズ付きであり、依然としてサイズ付きです。
  • [35:50] Sizedを自分で実装することは決してなく、自動トレイトとしてのみ使用されます。

コンパイラが既知のサイズを必要とする理由

  • [36:09] 問題はスタックサイズや、値がスタックに収まらないかもしれないかどうかではありません。
  • [36:18] マシンコードやアセンブリの層では、関数を呼び出すには、そのスタック変数、引数、戻り値のためにどれだけの領域を割り当てるかを知る必要があります。
  • [36:49] これを実現する巧妙な方法はありますが、コンパイラは効率的なコードを生成するためにこれらのもののサイズを知る必要があります。

サイズ不定型の例

  • [37:19] パラメータ型として使われる裸のトレイト、たとえば high を受け取る場合、多くの実装者が異なるサイズを持ちうるため、サイズ不定です。
  • [37:37] ここで impl を使うのはジェネリックパラメータの省略記法であり、静的ディスパッチと単相化によって具体的な型ごとに関数のコピーが存在するため、サイズは確定します。
  • [38:08] トレイトそのものを受け取る場合、din hi と書くのと同じですが、サイズ不定であるため動作しません。
  • [38:29] str を保持する構造体はサイズ不定です。文字列自体(それへのポインタではなく)は任意のサイズになりうるからです。参照のないスライスも同様に、要素数が不明なためサイズ不定です。
  • [39:01] これらのサイズ不定型をさらに含むものもすべてサイズ不定になります。

Sterling 2 の単相化問題を解決する

Sterling 2 向けの単相化しない手法の提案

  • [39:38] 話者は、この状況をどう解決できるかを尋ねます。
  • [39:40] 目標は、仮に「Sterling Din」と呼ばれる Sterling 2 用のバリアントを受け取れるようにすることです。
  • [39:49] 単相化されない、このような手法が求められています。

サイズ不定のトレイト型に対する間接化

ポインタを介してサイズ不定型をサイズ確定にする

  • [39:58] コツは、あらゆる内部型に対してそれ自体がサイズ確定である型を介して間接化することで、型を常にサイズ確定にすることです。
  • [40:17] 参照は常に同じサイズで、単にポインタのサイズ、場合によっては二つのポインタ分です。
  • [40:29] コンパイラは、後ろにどんな型が続いても参照の大きさを常に把握しています。単なるポインタだからです。
  • [40:43] box もヒープへの単なるポインタなので、間接化を使えば引数のサイズは判明します。

単相化せずにトレイトを使う

  • [40:54] 単相化せずにトレイトそのものを受け取るには、参照、box、arc などの何らかのポインタ型の背後に置きます。
  • [41:28] Box の定義では疑問符が使われており、T がサイズ確定である必要がないことを意味し、すべてはサイズ確定でなければならないという自動境界をオプトアウトしています。
  • [41:50] だからこそ、それ自体がサイズ不定であるものの box を作成できるのです。

ヒープ割り当てと具体的な型

  • [42:00] 最初に box を作成するとき、box に入れるもののサイズ分の割り当てを行います。
  • [42:48] ボックスを作るには、具体的な型を持つ何かを渡す必要があり、その時点でその型のためにヒープ領域が確保されます。
  • [42:57] ボックスは単なるポインタであるため、指し示す先が任意のサイズであっても、ボックス自体は既知のサイズのままです。
  • [43:13] 関数に実際に渡される引数にはサイズがあるため、関連するコードを生成できます。

ボックスと参照の比較

  • [43:57] Box<dyn AsteroidStir> を直接 x に置くのも問題ありませんが、Box::new には依然として具体的でサイズのある型を渡す必要がありました。
  • [44:23] 参照よりもボックスを選ぶための厳格な規則はありません。一般に、ボックスの利点は静的であり、呼び出し元のスタックフレームがなくなった後も動作し続けることです。
  • [44:44] スタック上の何かへの参照を関数に渡し、ポインタの間接参照を経由して、参照を受け取るものに渡すこともできます。
  • [45:41] 二重のアスタリスクが必要なのは、ボックスにもアスタリスクメソッドがあるためです。

Rust におけるトレイトオブジェクトと型消去

トレイトオブジェクトの定義

  • [46:17] 構築されたものはトレイトオブジェクトとして知られ、その唯一の特性はトレイトを表すことです。
  • [46:28] トレイトオブジェクトは、ラップしている型が何であっても、ある基底のトレイトとしてのみ振る舞います。
  • [46:44] ボックスはポインタ型です。

具体的な型への変換

  • [46:49] トレイトオブジェクトを元の具体的な型に戻すことは一般には不可能ですが、技術的には unsafe な transmute や any トレイトを介して可能な場合もあります。
  • [47:03] 値をトレイトオブジェクトに変換することは本質的に型消去です。以前どの型であったかの知識は消去されます。
  • [47:26] unsafe や any トレイトの魔法は一般に無視すべきです。

トレイトのメソッドのみが使用可能

  • [47:29] 変換後は、トレイトを使用する能力のみが保持され、具体的な型に関するその他の知識はすべて消去されます。
  • [47:39] ボックス化された ASRF stir では、ASRF を呼び出すことしかできず、それ以外は何もできません。

動的ディスパッチと vtable の仕組み

ジェネリック呼び出しのためのコンパイル時コード生成

  • [48:09] コンパイラが関数のマシンコードを生成するとき、最終的には実行可能なマシンコードに変換できるアセンブリを生成する必要があります。
  • [49:29] 一般的なケースでは、コンパイラは各具体的な型ごとにコードのコピーを取得するため、呼び出しはバイナリ内の既知のメモリ位置への直接ジャンプになります。
  • [50:05] 具体的な実装の場合、コンパイラはコンパイル時に静的にどこへ行くべきかを知っているため、コード生成は簡単になります。

トレイトオブジェクトと未知の具体的な型

  • [48:51] sayHi のような関数は Hi トレイトのトレイトオブジェクトを受け取りますが、これは実際には単なるポインタであるため、コンパイラは型 S が何であるかを知りません。
  • [50:14] 動的なケースでは、コンパイラは値が str なのか String なのかを知らないため、どのアドレスを生成すべきかを決定できません。

仮想ディスパッチテーブル

  • [50:29] この状況こそが、動的ディスパッチと v テーブル、すなわち仮想ディスパッチテーブルが活躍する場面です。

トレイトオブジェクトと動的サイズ型

トレイトオブジェクトポインタにおける追加の型情報

  • [50:38] トレイトオブジェクトを構築するということは、参照やボックスが単にポインタ一つ分の幅ではなく、指し示す型に関する追加情報を運ぶことを意味します。

動的サイズ型に関する Rust リファレンス

  • [51:24] Rust リファレンスには、ほとんどの型はコンパイル時に既知の固定サイズを持ち、Sized トレイトを実装していると記載されています。
  • [51:33] サイズが実行時にのみ判明する型は、動的サイズ型、あるいは非公式にサイズ不定型と呼ばれます。
  • [51:40] スライスとトレイトオブジェクトは、動的サイズ型の二つの例です。

実行時の型決定の例

  • [51:45] コンパイル時にはどの具体的な型が使われるか不明であるため、サイズは実行時にのみ判明します。
  • [51:58] ユーザーから読み取った値によって say_hi が数値を受け取るか文字列を受け取るかが決まる例では、実際の型は予測できない入力によって実行時にのみ決定されます。

動的サイズ型のポインタサイズ

  • [52:59] 動的サイズ型へのポインタ型はサイズを持ちますが、サイズ付き型へのポインタの二倍のサイズになります。

Rust におけるトレイトオブジェクトと Vtable

トレイトオブジェクト参照の構造

  • [53:09] トレイトオブジェクトへのポインタは、Vテーブルへのポインタも格納します。
  • [53:23] dyn Hiのようなトレイトオブジェクトへの参照は、具体的な実装型へのポインタと、参照されたトレイトのVテーブルへのポインタを格納します。

Vテーブルに含まれるもの

  • [53:52] Vテーブル(仮想ディスパッチテーブル)は、その型に対するトレイトの各メソッドへのポインタを保持するデータ構造です。
  • [54:10] dyn Hiの場合、Vテーブルはメンバーを一つ持つHi Vテーブル構造体と考えることができます。そのメンバーhiは、Tが何であれそのTへのポインタを受け取るFnへのポインタです。
  • [54:47] トレイトオブジェクトに変換される具体的な型ごとに、異なるVテーブルが構築されます。

変換時のVテーブルの構築

  • [54:57] strをdyn Hiに変換すると、strへのポインタと、hiがstr as hiであるHi Vテーブルが得られます。
  • [55:38] 変換の際、コンパイラはVテーブルを構築し、そのアドレスを参照内に格納します。
  • [55:59] TraitObjectに変換される型ごとに、そのようなVテーブルが一つ存在します。

生成されるディスパッチコードと型ごとのVテーブル

  • [56:10] 生成されるコードはs.VTable.Hi(s.Pointer)のようなものです。
  • [56:25] 代わりに文字列が渡された場合、s.Vtableは別のポインタになり、12行目のstr as hiではなく6行目のstring as hiを指します。
  • [57:07] 生成されるコードは、Vテーブルを介して間接参照し、各型がそれぞれ固有のVテーブルを持つため、どの型が渡されても動作します。

RustのVテーブルとトレイトオブジェクトのレイアウト

Vテーブルの構築とファットポインタ

  • [57:45] Vテーブルは動的に割り当てられるのではなく、コンパイル時に静的に構築されます。
  • [58:01] トレイトオブジェクトはポインタを一つではなく二つ含むため、ファットポインタ(ワイドポインタ)です。
  • [58:16] 二つ目のポインタは、トレイトオブジェクトの元の構築によって決まるため、一般に静的に既知です。ただし、技術的にはVテーブルをその場で手動で構築することも可能です。

トレイトオブジェクトにおける文字列スライスの表現

  • [58:51] 参照は文字列スライスの長さも含んでいます。
  • [59:06] ポインタは実際の文字列ではなく、それ自体が長さを保持するstr参照を指します。

vtableの内容とデバッグ

  • [59:23] 話者は、コンパイラにvtable構造体を出力させる方法を知りません。
  • [59:33] vtableには対応するトレイトの各メソッドごとのメンバーがあり、各メンバーの値はその具象型におけるそのメソッドの実装へのポインタです。

vtableの同一性と重複排除

  • [1:00:12] インスタンスが作成されるたびに新しいvtableが構築されるわけではなく、vtableは一般にその型に対して静的に構築されます。
  • [1:00:32] 同一のvtableは重複排除されず、二つの異なる型に対するトレイトの実装は、同じコードを含んでいても異なることが保証されるため、異なるアドレスを持ちます。

トレイトオブジェクトにおけるBoxとポインタの幅

  • [1:01:09] Box<dyn Trait>は、ワイドポインタへのシンポインタではなく、Box自体がワイドポインタです。
  • [1:01:26] Boxは特別ではなく、内部にdyn参照を含んでおり、Rustコンパイラはトレイトオブジェクトへの参照とポインタが幅2であることを知っているため、Box<dyn Trait>自体がワイドであり、余分な間接参照はありません。

複数のトレイトを持つトレイトオブジェクトとvtableの限界

二つのトレイトの組み合わせが失敗する理由

  • [1:04:12] HiとAsRefを組み合わせたトレイトオブジェクトが機能するには、コンパイラがhiメソッドとasrefメソッドの両方がどこにあるかを知る必要がありますが、それらは二つの異なるvtableに存在します。
  • [1:04:29] これには二幅のポインタではなく三幅のポインタ、すなわちデータへのポインタ、Hi用のvtableへのポインタ、AsRef用のvtableへのポインタが必要になります。
  • [1:04:44] そのようなレイアウトは本質的に不可能ではありませんが、トレイトを追加するたびに参照のサイズが大きくなり続けることになり、おそらく意図されたものではないでしょう。

コンパイラが生成する結合vtableとスーパートレイトによる回避策

  • [1:04:59] 理論上、コンパイラは組み合わせ用のvtableを生成して渡すことができますが、現在のRustコンパイラはこれを行わず、話者はそうするための提案を知りません。
  • [1:05:11] 回避策として、型がHiとAsRefStrの両方であることを要求し、自身のメソッドを持たないHiAsRefのようなトレイトを宣言すると、両方のトレイトのメソッドを含む単一のより大きなvtableが得られます。
  • [1:05:52] これがRust自体に取り入れられていない理由の一部は、自分でオプトインできることであり、プラスを自動的に大きなvtableに変えないことで、これが開発者の意図したものではなかったかもしれないということを開発者に示すためです。

複数のトレイトに対するコンパイラエラーと提案

  • [1:06:45] Hi + AsRefStrと書くと、HiもAsRefStrも自動トレイトではないため、トレイトオブジェクトの追加トレイトとして使用できるのは自動トレイトのみであるというエラーが発生します。
  • [1:07:14] コンパイラは、これらすべてをスーパートレイトとして持つ新しいトレイトを作成し、代わりにここでそのトレイトを使用することを提案し、SendやSyncのような自動トレイトは問題ないと指摘します。

マーカートレイトとメソッドを持たない追加のトレイト

  • [1:07:27] Sendのようなメソッドを持たないマーカートレイトでは、vtableが空でも問題ないため、vtableの追加部分を保存する必要はありません。
  • [1:07:49] 講演者は、ユーザー定義のトレイトをこのように使用できるとは考えていませんが、トレイトがメソッドを決して持たないことを宣言するマーカー注釈の提案はありましたが、現在は存在しません。

トレイトオブジェクトと関連型

関連型がトレイトオブジェクトのコンパイルを壊す

  • [1:08:51] トレイトhighにnameという関連型を追加すると、たとえ未使用であっても、コードはコンパイルされなくなります。
  • [1:09:28] コンパイラは、dyn highを取る場所でトレイトhighの関連型nameの値を指定する必要があると報告します。
  • [1:09:39] 関連型に関係なく任意のhighを受け入れることはできません。その型情報はvtableに取り込むことができないためです。

関連型を指定してコンパイルを復元する

  • [1:09:50] 関連型はバイナリ内にアドレスを持たないため、vtableに配置できるものがなく、トレイトオブジェクトで直接動作しない理由です。
  • [1:10:01] 修正方法は、nameが指定された型であるhighを取ることであり、他の場所でも同じ制約を適用します。
  • [1:10:16] これは、その関連型をnameとしてhighを実装するもの専用のvtableが存在するため、機能します。

トレイトオブジェクトの安全性とvtableメソッドのオプトアウト

selfのない関連関数がオブジェクト安全性を壊す理由

  • [1:11:20] コンパイラは、トレイトをオブジェクトにできないと報告します。つまり、オブジェクト安全ではなく、トレイトオブジェクトになれません。
  • [1:11:34] トレイトがオブジェクト安全であるためには、呼び出しを動的に解決できるようにvtableを構築できる必要があります。
  • [1:11:44] エラーは具体的に、関連関数weirdにselfパラメータがないため、トレイトをオブジェクトにできないと述べています。
  • [1:12:17] weirdはselfやポインタを取らず、指すべき有効なインスタンスが存在しないため、s.weirdを呼び出すことはできません。
  • [1:12:36] デフォルトが存在しても、どの実装を使用するかを指定するものがないため、Hi::weirdとして呼び出すのは曖昧です。
  • [1:13:14] selfがないため、メソッドはvtableに入れることができず、どの型のインスタンスにも関連付けられません。

where Self: Sizedでメソッドをvtableからオプトアウトする

  • [1:14:21] weird に where Self: Sized 制約を追加すると、実装する型が Sized であることが要求され、dyn Hi のようなトレイトはポインタの背後にない限り Sized ではありません。
  • [1:14:43] これにより、この関数は実質的に vtable から除外され、決定的なことにトレイトオブジェクト経由で呼び出せなくなります。
  • [1:15:06] この制約があればコードはコンパイルされ、トレイトオブジェクトを依然として作成でき、Hi を呼び出せます。
  • [1:15:30] その場合、メソッドにサイズ要件があるため、トレイトオブジェクト上で weird を呼び出すと失敗します。
  • [1:15:38] これが、任意の関数を対象から除外してトレイトのオブジェクト安全性を保つ方法です。

トレイト全体でトレイトオブジェクトを禁止する

  • [1:15:50] トレイト全体に where Self: Sized を追加すると、そのトレイトをトレイトオブジェクトとしてまったく使えなくなります。
  • [1:16:07] これは実際にはまれで、通常はメソッドのせいで単にオブジェクト安全でなくなるだけです。
  • [1:16:22] 後方互換性のためにこれを行うことがあり、後でオブジェクト安全でないメソッドを追加する可能性を考えて先回りして追加します。

関連型と静的ディスパッチに関する聴衆からの質問

  • [1:16:50] 話者は、関連型の問題が静的ディスパッチでも発生するのかと尋ねます。

Rust のトレイトオブジェクト、静的ディスパッチ、関連型

静的ディスパッチと単相化

  • [1:16:54] 静的ディスパッチでは、単相化により各関数実装の具体的な型が判明します。

トレイトオブジェクト上の仮想的な静的メソッド

  • [1:17:06] `s::weird` のような構文が可能で、`weird` は vtable に含まれるが self 引数なしで呼び出されるかもしれません。
  • [1:17:41] 話者はこれを奇妙に感じます。呼び出すのにその型のインスタンスがどうせ必要なら、単に self を取ればよいのではないかと。
  • [1:17:53] 伝統的な例は `new` のようなメソッドで、すでにインスタンスがあるなら呼び出す必要はないため、単に self を取るだけです。
  • [1:18:11] 話者は、このようなことは可能かもしれないが、実際には通常あまり有用ではないため優先されていないことに同意します。より深い理由があるかもしれませんが、話者には確信がありません。

`where Self: Sized` と具体的な DST

  • [1:18:47] `where Self: Sized` を持つトレイトでも、`Box<dyn ...>` のようなものに対して実装できると話者は考えています。
  • [1:19:11] そのようなトレイトはもはやトレイトオブジェクトにはできませんが、実装は依然として可能なはずです。
  • [1:19:24] ボックスなので二重参照が必要ですが、ボックス化された型は動的サイズではないため問題ありません。ポインタの背後に包むことでサイズが与えられるので、トレイト上の`Self: Sized`があってもそれを妨げません。
  • [1:20:46] 質問が`str`や`u8`のような型を意味していたなら、それはできません。`where Self: Sized`がある場合、Selfはサイズ付きでなければなりません。

vtableにおける型消去と関連型

  • [1:19:53] 関連型の制限は奇妙に感じます。なぜなら、具体的な型ごとに関連型は一つしか存在しないので、vtableはそれが何であるかを知っているはずだからです。
  • [1:20:07] 問題は型が消去されていることです。残るのはvtableだけなので、vtableから具体的な型がかつて何であったかを知ることはできません。
  • [1:20:18] `any`トレイトは例外で、かつての具体的な型の記述子を返すメソッドがあるため、これを回避する方法がいくつかあります。
  • [1:20:35] トレイトオブジェクトは型消去されるため、かつての型に関する情報を保持することはできません。

標準ライブラリのfromIteratorとcollect

fromIteratorトレイトとcollect

  • [1:21:02] 話者はメソッドをジェネリックにできないと指摘し、カスタムのhighトレイトを続ける代わりに標準ライブラリのfromIteratorトレイトに目を向けます。
  • [1:21:16] fromIteratorトレイトは、他の型と同様にVecによって実装されています。
  • [1:21:21] collectが機能するのは、VecがfromIteratorを実装しているからです。
  • [1:21:30] イテレータでcollectを呼び出すには、対象の型がfromIteratorを実装している必要があります。

RustのFromIteratorとExtendトレイトの仕組み

FromIteratorトレイトの型パラメータ

  • [1:21:38] イテレータをVecにcollectできるのは、VecがFromIteratorを実装しているからです。
  • [1:21:49] FromIteratorの関連型Aはイテレータの要素の型なので、その要素型のVecが得られます。
  • [1:22:00] トレイトのジェネリックパラメータTはイテレータ自体の型で、例えばHashMapのイテレータ型などです。
  • [1:22:10] Vec<T>は、具体的なイテレータ型に関係なく、要素がTである任意のイテレータから構築できます。
  • [1:22:20] 話者は、パラメータはおそらくiterのIと名付けるべきだと指摘しますが、重要ではないと考えています。

FromIteratorにおけるトレイトオブジェクトの問題

  • [1:22:43] FromIteratorを使うと、トレイトオブジェクトにとって問題が生じます。
  • [1:23:35] boolのFromIteratorを受け取りVecを返す関数は問題ないように思えます。
  • [1:23:45] FromIteratorはselfを取らないため、selfがサイズ付きである必要があるので、悪い例です。

より良い例としてのExtend

  • [1:23:53] 話者はより良い例としてExtendに切り替えます。
  • [1:24:04] Extendは可変のselfを取るため、コードはVec::newで可変のVecを作成します。
  • [1:24:25] Vecはv.extendを介して単一のboolであるtrueで拡張されます。
  • [1:24:39] この関数はboolのイテレータで拡張できるものを受け取ります。

Extendがオブジェクト安全でない理由

ジェネリックなExtendメソッドと単相化

  • [1:25:05] Extendはイテレータの要素型に対してジェネリックであり、selfを取りますが、メソッドはイテレータ型に対してもジェネリックです。
  • [1:26:28] 単相化のため、コンパイラは単一のextendメソッドを生成せず、イテレータ型と要素型の組み合わせごとに複数のコピーを生成します。
  • [1:27:27] 単一のextendは存在せず、イテレータ型と要素型のすべての組み合わせに対して存在します。

選択された実装に対するvtableエントリの欠如

  • [1:27:42] 要素型Tはすでにboolとして固定されていますが、vtableにはbool上の特定のイテレータ型に対するextendへのポインタが依然として必要です。
  • [1:28:05] そのイテレータ型は関数の型に表現されておらず、書かれている通りに表現する方法はありません。
  • [1:28:42] コンパイラがコードを生成しようとすると、適切なextend実装へのポインタがないため、vtableを生成できません。

無限のvtableとトレイトオブジェクトの不在

  • [1:28:52] dyn Extendのvtableには、可能な各extend実装に対して一つずつ、無限の数のエントリが必要になります。
  • [1:29:04] したがってdyn Extendは存在できず、Extendのトレイトオブジェクトを作成することはできません。

呼び出しごとの単相化されたvtableが失敗する理由

  • [1:29:26] 各Tに対して単相化されたextendをすべての実装型に追加するのは魅力的ですが、常に可能とは限りません。
  • [1:29:43] 標準ライブラリに依存するクレートはより多くの型でextendを呼び出す可能性があるため、dyn Extendのvtableは標準ライブラリと上位のクレートで異なることになります。
  • [1:30:18] これはdyn Extendに対して異なるvtableの組み合わせ爆発を引き起こし、標準ライブラリのdyn Extendを上位のクレートのコードに渡すことを妨げます。なぜなら、それらのvtable型が異なるからです。

オブジェクト安全性とCloneトレイト

オブジェクト安全なトレイトの要件

  • [1:31:01] トレイトがオブジェクト安全であるためには、ジェネリックメソッドを持ってはなりません。
  • [1:31:10] そのすべてのメソッドは、selfを含むレシーバを持つ必要があります。
  • [1:31:17] また、トレイトはselfを返す型を持つこともできません。

Cloneがトレイトオブジェクトになれない理由

  • [1:31:38] dyn Cloneでは、トレイトが許すことしかできず、Cloneはクローンを作ることしか許しません。
  • [1:31:47] コンパイラは、トレイトCloneをオブジェクトにできないと報告します。
  • [1:31:58] Cloneには、selfを取りselfを返すfn cloneがあります。

サイズ不定の戻り値型の問題

  • [1:32:03] let x = v.clone()の場合、dyn Cloneはクローン可能な任意の型にすぎないため、xのサイズは不明です。
  • [1:32:19] Cloneはdyn Cloneへの参照ではなく、selfを返すことになっています。
  • [1:32:26] 具体的な型が消去されるため、selfはdyn Cloneとなり、これはサイズ不定です。
  • [1:32:46] 関数の戻り値型はコードを生成するためにサイズが定まっている必要があるため、これは機能しません。
  • [1:32:51] したがって、トレイトがオブジェクト安全であるためにはselfを返すメソッドを持てず、これがCloneを使用できない理由です。

オブジェクト安全なメソッドとそうでないメソッドの混在

  • [1:33:05] トレイトの一部のメソッドはオブジェクト安全であり、それ自体で依然として有用です。
  • [1:33:12] 他のメソッドはトレイトをオブジェクト安全でなくするかもしれませんが、トレイトオブジェクトを経由しない型のために必要とされます。

where Self: SizedによるIteratorトレイトのオブジェクト安全性

Iteratorのジェネリックメソッドとオブジェクト安全性

  • [1:33:23] Iteratorトレイトには関連型Itemとオブジェクト安全なメソッドnextがありますが、chain、enumerate、by_ref、およびFromIteratorに依存しオブジェクト安全でないcollectなどのジェネリックメソッドもあります。
  • [1:34:01] それでも Iterator はオブジェクト安全です。dyn Iterator<Item = bool> では collect をトレイトオブジェクト上で呼び出すことはできませんが、next は可変レシーバで呼び出せます。

where Self: Sized はメソッドを vtable から除外します

  • [1:35:03] self を消費する count や last といったメソッドには where Self: Sized 境界が付き、汎用の chain メソッドにも同様に付きます。
  • [1:35:27] where Self: Sized 境界は、トレイトをトレイトオブジェクトとして使う際にその関数を無視するようコンパイラに指示するため、vtable には配置されません。
  • [1:35:44] したがってトレイトオブジェクトはそのようなメソッドを呼び出せませんが、Vec のイテレータのような具体的な型は呼び出せます。これにより、トレイト全体をオブジェクト安全でなくすることなく、あると便利なメソッドをトレイトに残せます。

許可されるレシーバ型に関する質問

  • [1:36:13] 話者は、レシーバは self を含む任意のものでよいのか、それとも &self または &mut self でなければならないのかと尋ねます。

Rust のオブジェクト安全規則とトレイトオブジェクト

スーパートレイトと関連定数

  • [1:36:37] すべてのスーパートレイトもオブジェクト安全でなければなりません。vtable はすべてのスーパートレイトの和集合から構築されるためです。
  • [1:36:45] self: Sized を要求するとトレイトはオブジェクト安全でなくなります。Sized がスーパートレイトにならないためです。
  • [1:36:52] オブジェクト安全なトレイトは関連定数を持ってはなりません。置く場所がないためです。vtable に置くと非常に大きくなり、その値はもはやすべて関数ポインタではなくなります。

ディスパッチ可能な関数とディスパッチ不可能な関数

  • [1:37:12] すべての関連関数は、トレイトオブジェクトからディスパッチ可能であるか、明示的にディスパッチ不可能でなければなりません。
  • [1:37:19] ディスパッチ可能な関数は型パラメータ(ジェネリクス)を持ってはならず、レシーバ型以外で具体的な self 型を使ってはならないため、関数は self を返せません。
  • [1:37:32] レシーバは self への参照、self への可変参照、Box<Self>、Rc<Self>、Arc<Self>、または Pin<&Self> のみでかまいません。つまり、サイズなしの値をサイズありの値に変換できるポインタの背後にあるものであればよいのです。
  • [1:37:55] これは where Self: Sized 境界を明示的に除外するもので、一部のメソッドがそうでなくてもトレイトをオブジェクト安全にできるようにします。

where Self: Sized を追加する際のアドバイス

  • [1:38:14] ライブラリの作者は、下流のユーザーがトレイトオブジェクトを望む場合に備えて、オブジェクト安全でないメソッドに where Self: Sized を追加することを一般に検討すべきです。
  • [1:38:23] それはトレイトがそもそもトレイトオブジェクトとして使えるかどうかによります。Clone のようなものでは、境界を追加するとトレイトオブジェクトを作れるようになりますが、その主要な関数を呼び出せなくなるため、おそらく価値はありません。
  • [1:38:48] オブジェクト安全なメソッドだけを呼び出せる場合でもトレイトが有用であれば、他のメソッドをオプトアウトしてトレイト全体をオブジェクト安全にするのは理にかなっているかもしれません。

Iterator::last と Sized 制約

  • [1:39:14] Iterator::last には確かに Sized 制約がありますが、rustdoc では隠されています。
  • [1:39:25] last には where Self: Sized が付いています。これは self を参照の背後に取るのではなく消費するためです。Self は Sized でないイテレータであり、関数の引数は Sized でなければならないため、last はトレイトオブジェクトを通して呼び出すことはできません。

トレイトオブジェクトに関する秘密

  • [1:39:55] 講演者は、トレイトオブジェクトについてまだ説明していないことが少なくとも一つあると述べています。トレイトオブジェクトに関するちょっとした秘密です。

Drop とトレイトオブジェクトの vtable

オブジェクト安全なトレイトとしての Drop

  • [1:40:16] Drop は実際にはオブジェクト安全です。ドロップできるだけのオブジェクトは面白くないように思えるかもしれませんが。
  • [1:40:26] これは、ガベージコレクションのように、オブジェクトがすぐにドロップされず、連結リストに格納されて定期的に回収される状況で役立ちます。
  • [1:40:43] 多数の潜在的に異なるものを一つの型に格納するには TraitObjects が必要なので、Crossbeam はそれらを drops に格納します。技術的には boxed で drops に格納し、同じ効果を得ています。

vtable を通した Drop

  • [1:40:59] v がスコープを外れると、dropDrop が vtable を通して呼び出されます。
  • [1:41:34] box 化された s がスコープを外れると、ヒープ割り当てが存在し、関数の戻り時に s がドロップされる前に s.asref を通して使用される可能性があります。
  • [1:41:56] box をドロップするにはメモリを解放する必要がありますが、唯一のメソッドが asref であるトレイトオブジェクトでも、それを行う方法が必要です。
  • [1:42:06] すべての vtable には drop が含まれているため、任意の TraitObject の vtable には、具体的な型の drop 関数へのポインタが含まれており、これが必要です。

vtable におけるサイズとアラインメント

  • [1:42:27] vtable には技術的には具体的な型のサイズとアラインメントも含まれています。
  • [1:42:34] この情報は、メモリを解放するためにアロケータに渡す必要がある box のようなものに必要です。
  • [1:42:44] すべてのトレイトオブジェクトの vtable には、トレイトのメソッドに加えて drop、サイズ、アラインメントが含まれています。

Rust におけるサイズなし型とワイドポインタ

トレイトオブジェクト以外のサイズなし型

  • [1:43:04] トレイトオブジェクト以外にも、[u8] や str など、サイズなしの型があります。
  • [1:43:20] 参照やポインタの背後に置かれると、トレイトオブジェクトはデータポインタとvtableポインタのタプルになります。
  • [1:43:34] ポインタの背後のスライスは、データポインタとスライス長を保持するusizeからなるワイドポインタになります。
  • [1:43:50] 同様に、ポインタの背後のstrはデータポインタとusizeの長さとして表現されます。

サイズ不定の引数と戻り値に対するコンパイラエラー

  • [1:43:57] [u8]を値で受け取る関数は拒否されます。なぜなら[u8]型の値のサイズは不明であり、[u8]は任意の長さのu8のリストだからです。
  • [1:44:21] 裸の[u8]を返すことも失敗します。関数の戻り値型は静的に既知のサイズを持たなければならないからです。

参照とBoxでサイズ不定性をマスクする

  • [1:44:59] サイズ不定からサイズ付きへは、参照やBoxなどサイズ不定性をマスクする型の背後に値を置くことで行います。
  • [1:45:33] スライスをBox化するのは問題ありません。今はサイズ付きであり、データと長さを部分として持つワイドポインタだからです。
  • [1:45:43] コンパイラは型がアクセスされたときに長さを得るためにポインタを分解することを知っており、同じことがBox、生ポインタ、Stringにも当てはまります。

Rustのサイズ不定型とファットポインタのメタデータ

動的サイズ型に関するコンパイラの課題

  • [1:46:04] 動的サイズ型は、ポインタがワイドかどうかをコンパイラが知る必要があるため、コンパイラ内でやや特殊です。
  • [1:46:14] サイズ不定型を自分で扱うのはかなり難しく、サイズ不定型に対してboxのようなものを実装することは可能です。
  • [1:46:27] キャストやトレイトオブジェクトの許可が関わると面倒になります。

RFC 2580とPointyトレイト

  • [1:46:33] 最近承認されたRFC番号2580は、ファットポインタのメタデータを操作するための汎用APIを追加します。
  • [1:46:48] このAPIでは、ファットポインタの二番目の部分の型を指定できます。
  • [1:46:58] DINトレイトはpointyトレイトになり、そのメタデータはDINメタデータ、すなわち型のサイズ、アラインメント、dropとplaceのポインタ、メソッドポインタを保持するvtableへのポインタです。
  • [1:47:28] pointyトレイトは同様に、参照なしのU8スライスに対しても、メタデータとしてUサイズの長さを持つ形で実装できます。

実験的ステータスとThinトレイトエイリアス

  • [1:47:44] この機能はまだ新しく実験的であり、講演者はRFCを読むことを勧めています。
  • [1:47:52] このRFCには、空のメタデータを持つpointyを実装する任意の型に対するトレイトエイリアスthinが含まれています。つまり、fatポインタではなくthinポインタです。

メタデータのイントロスペクションと実行時Vtable

  • [1:48:08] このRFCは、vtableを調べるなど、ポインタのメタデータをイントロスペクションするためのメソッドを提供します。
  • [1:48:18] コンパイル時には不明で実行時に構築されるvtableをオンザフライで構築できることが極めて重要です。

手動Vtableの例としてのRaw Waker

  • [1:48:32] 実行時のvtable構築は、標準ライブラリの一箇所、asyncのwakerですでに存在しています。
  • [1:49:14] Contextは、wake、wake by ref、willWake、fromRawメソッドを持つWaker構造体を提供し、dropとcloneも可能です。
  • [1:49:29] Wakerの内部にはRawWakerがあり、これはデータポインタとvtableポインタで、隠れた形で動的ディスパッチを提供します。
  • [1:49:54] RawWakerのvtableは、clone、wake、wake by ref、dropの関数ポインタを提供することで構築され、実質的にはトレイトではなく型を通じて動的ディスパッチを提供する手動構築のvtableです。

RustのDST、スライス、Box対Vec

スライスのメタデータとカスタム動的サイズ型

  • [1:50:38] 講演者は、u8スライスへの参照が開始ポインタと終了ポインタを格納するのか長さを格納するのか確信が持てず、両者は基本的に同等だと述べています。
  • [1:51:01] 参照されたRFCは、Nightlyに存在するtrait objectとraw parts itemsからのthinメタデータを非推奨にしています。なぜならそれが置き換えだからです。
  • [1:51:29] 講演者は、RFCがスライスの関連メタデータ型を明記することを望んでいましたが、見当たらず、単に長さだと考えています。
  • [1:51:46] 独自の動的サイズ型をある程度作ることができます。最後のフィールドにu8スライスを持つ構造体はunsizedになります。
  • [1:52:14] 構造体の最後のフィールドのみが動的サイズ型を持てます。なぜなら、先行する型が任意のサイズを持つ場合、中間フィールドのオフセットを計算できないからです。
  • [1:53:07] unsizedフィールドが最後であれば、それ以前のフィールドのオフセットは静的に既知であり、型をsizedにするには最後のフィールドの長さだけが必要です。
  • [1:53:18] そのような構造体への参照は、ポインタと最後のフィールドの長さを一緒に格納することでsizedになります。

Box<[u8]>対Vec<u8>

  • [1:53:42] 参照の背後にないボックス化されたu8スライスは、Vec<u8>と同じように感じられても、同じではありません。
  • [1:54:11] Vecは三つのワードです。ヒープベクタへのポインタ、その長さ、その容量であり、容量内でのpushは長さを増やすだけです。
  • [1:54:32] Vecの容量を超えてpushすると、ベクタ全体が再割り当てされ、コピーされてから変更されます。
  • [1:54:39] ボックス化されたu8スライスは決して拡大も縮小もできず、プッシュすることもできません。それは本当にただのスライスです。
  • [1:54:49] Vec<u8>はBox<[u8]>に変換でき、また元に戻せますが、それらは同じ型ではありません。

Rustにおけるdyn fnとfnとimpl fnの比較

単なる関数ポインタとしてのfn

  • [1:55:53] fnパラメータは関数でなければならず、クロージャにはできません。なぜならfnは実際にはアドレスを保持する単一の関数ポインタにすぎないからです。
  • [1:57:35] barは実際の関数ポインタを要求するため、クロージャを渡すことはできません。キャプチャしたデータを格納する場所がないからです。

ワイドポインタのトレイトオブジェクトとしてのdyn fn

  • [1:56:02] dinfnは、vtableが関数を呼び出すためのポインタを保持するトレイトオブジェクトであり、データポインタも含むワイドポインタです。
  • [1:57:10] fooはxをキャプチャするクロージャで呼び出すことができます。呼び出し時にクロージャがxのアドレスをワイドポインタのデータ部分を通じて供給される必要があるからです。

ジェネリックな単相化としてのimpl fn

  • [1:58:24] bazはクロージャで呼び出すことができます。implfnはfnであるものすべてに対するジェネリック関数の糖衣構文であり、渡されたクロージャ型ごとにbazの具体的なコピーを生成するからです。
  • [1:58:40] bazは個々のクロージャごとに単相化されるため、キャプチャしたデータを簡単に渡すことができます。

impl fnとdyn fnの選択

  • [1:58:53] implfnはより一般的に使用でき、ポインタを介した間接参照を避けられますが、渡されたクロージャ型ごとにbazのコピーを生成するため、かなり多くなる可能性があります。
  • [1:59:12] ジェネリクスの代わりにトレイトオブジェクトが好まれることがあります。そうしないとジェネリック型を呼び出し元まで伝播させる必要があるからです。
  • [1:59:51] ラッパー構造体がfに対してジェネリックである代わりにbox din fnを格納する場合、ラッパーはもはやジェネリックではないため、呼び出し元はジェネリックパラメータを名指ししたり伝播したりする必要がなくなり、インターフェースを整理できます。

fnパラメータを持つトレイトのオブジェクト安全性

  • [2:00:19] fooがimpl fnを取るトレイトxはオブジェクト安全ではありません。implfnはジェネリックなf is fnと等価であり、これをオブジェクト安全にすることはできないからです。
  • [2:01:07] 代わりにfooがdinfnを取る場合、トレイトはオブジェクト安全にできます。fooが一つしかなく、無限のvtableエントリの必要性を避けられ、foo自体が任意のオブジェクト安全な型で機能するワイドポインタを取るからです。

コヒーレンスは延期。ディスパッチ、vtable、トレイト検出に関するQ&A

コヒーレンスを別のストリームに延期

  • [2:02:00] コヒーレンスはカバーされず、十分に異なるため、話者はそれについて別のストリームを行うかもしれません。
  • [2:02:15] 配信は約二時間のところなので、講演者はここで止めてコヒーレンスを別に扱うのが良いタイミングだと考えています。

ディスパッチとトレイトオブジェクトの概念のまとめ

  • [2:02:29] 講演者は、静的ディスパッチと動的ディスパッチの一般的な違い、サイズトレイト、vtable、オブジェクト安全性、ワイドポインタとファットポインタについて、おおよそ理解できたかどうかを尋ねます。
  • [2:02:45] 講演者は、これらがなぜ存在するのか、何のためのものか、どのような制限があるのかを明確にするために、さらに資料を進めることを提案します。

vtableを介した実行時のトレイト検出が不可能な理由

  • [2:03:00] 将来vtableを使って実行時のトレイト検出を実装できるかという質問に対して、講演者はできないと考えていると述べています。
  • [2:03:30] トレイトオブジェクトごとに異なるvtableが生成されるため、strやstringに対して一つのvtableがあるのではなく、stringに対してdynトレイトごとに多くのvtableがあります。
  • [2:04:02] dynトレイトであるSを受け取る関数の場合、vtableには指定されたトレイトのメソッドのみが含まれ、提供された型のすべての可能なメソッドは含まれません。
  • [2:04:30] したがって、講演者はこの方法で何かがどのトレイトを実装しているかを動的に検出することはできないと考えています。

dyn Fn呼び出しにおける二重間接参照

dyn Fnのワイドポインタレイアウト

  • [2:05:23] 引数がポインタとvtableのタプルへのポインタではなくワイドポインタであるため、この呼び出しは厳密には二重間接参照ではありません。
  • [2:05:33] 渡されるのは、型が不明な何らかのTへのポインタと、TのFn vtableへのポインタです。

callに到達するためのvtableの間接参照

  • [2:05:56] 呼び出しは実質的にtのVtable.callになるため、callに到達するにはvtableポインタを間接参照する必要があります。
  • [2:06:28] vtableを間接参照して呼び出すcallのアドレスを見つけるため、結局二回の間接参照になります。
  • [2:06:35] それでも、厳密にはポインタチェイシングではありません。

動的ディスパッチ、vtableのトリック、ジェネリックの最適化

ダウンキャストのためのvtableの比較

  • [2:07:02] AsRef<str>を実装する型Xについて、新しいポインタvtable動的メタデータRFCでは、s.vtableとstringのAsRef<str>実装のvtableを比較できるようになるかもしれません。
  • [2:07:41] vtableが一致すれば、データ参照をstring参照にキャストでき、可変参照の場合はpushを呼び出せますが、講演者はこれを行わないことを勧めています。
  • [2:08:07] 講演者は、コンパイラが型が常にちょうど一つのvtableを持つことを保証しているかどうか確信が持てません。

ジェネリクスと動的ディスパッチ最適化の比較

  • [2:08:18] コンパイラはかなりの量の最適化を行うため、ボックス化されたdyn fnが常にヒープ確保を行うとは限りません。エスケープ解析などの手法により回避されることがあります。
  • [2:08:31] ジェネリック型パラメータやimplトレイトを使用すると、コンパイラが関連する型をコンパイル時に完全に把握でき、具体的な実装に基づいて共同最適化できるため、一般により良い最適化が得られます。
  • [2:08:52] 動的ディスパッチを介した間接参照では、コンパイラは最適化に使えたはずの情報の一部を失います。

スライスの例のリクエスト

  • [2:09:07] 視聴者がdynのVecのスライスの簡単な例を求めています。

Rustのトレイトオブジェクト、vtable、Anyトレイト

dyn AsRef配列をサイズ付き要素で動作させる方法

  • [2:09:15] HとSにdyn AsRef<str>のようなものを使うには、配列の要素を同じサイズにする必要があります。配列は特定のインデックスを見つけられるようにするため、それを要求するからです。
  • [2:09:56] 要素を同じサイズにすれば、このアプローチはそのまま動作し、内側の型にBoxやArcなどを入れることもできます。

コンパイル単位間でvtableが異なり得る理由

  • [2:10:08] 異なるコンパイル単位では異なるvtableが生成されることがあります。
  • [2:10:12] 経験的に、Rustは一つのクレートを複数の独立したスレッドでコンパイルし、異なる部分集合を並行してコンパイルすることでコンパイルを高速化することがあります。
  • [2:10:25] これらの分離された単位はほとんど同期せずに並行して動作するため、両方がdyn AsRefとして使われる文字列に遭遇し、調整せずにそれぞれ独自のvtableを生成する可能性があります。
  • [2:10:40] これにより、同じ型と同じトレイトに対しても複数のvtableが生成されることがあり、これが不変条件が成り立たない可能性がある一例です。

Anyトレイトがダウンキャストを可能にする仕組み

  • [2:10:57] Anyトレイトは非常に魔法のようだと説明されますが、実際にはコンパイラによって一意性が保証された型識別子を返す関数を持つ単なるトレイトです。
  • [2:11:19] Anyに対するトレイトオブジェクトがあれば、vtableに追加されるため、その値の一意な型識別子を取得して型IDを使うことができます。
  • [2:11:28] その識別子により、型識別子が何であるかがわかるため、dyn Anyから具体的な型へダウンキャストできます。
  • [2:11:46] Anyは、これまで議論してきた仕組みの多くを使って、dynトレイト(そのトレイトがAnyを含む限り)から実際の基底型への参照へと変換します。

Anyの安全性に関する推奨文献

  • [2:12:02] 講演者は、基礎となる概念を理解すればAnyは驚くほどシンプルだと述べ、標準のAnyModuleドキュメントを読むことを勧めています。
  • [2:12:12] そのドキュメントには、これがなぜ安全なのかが書かれています。

配信のまとめと今後のコーディング計画

セッションの締めくくりと長さ

  • [2:12:17] 話し手はおよそ2時間15分でセッションを終え、かなり満足していると述べています。
  • [2:12:22] 彼は多くのことを扱ったと述べ、それが役に立ち、一部でも身につけばいいと願っています。

予定されているコーディングのライブ配信

  • [2:12:30] 彼は、ぜひ実現したいコーディングのライブ配信について少し進展があったと述べ、できるだけ早く実現することを願っています。
  • [2:12:39] 彼はその計画を忘れておらず、今も取り組んでいると述べています。

最後の感謝

  • [2:12:44] 彼は来てくれた皆に感謝し、また次回会いましょうと述べています。

タイムスタンプ付きの既存字幕を無料で閲覧し、ポッドキャストや講義も TXT・SRT・Markdown で保存できます。無料 YouTube 字幕抽出ツール。

冒頭 3 段落の二言語対訳プレビュー · 利用枠の消費なし

保存済みの日本語訳と英語原文の冒頭 3 段落を並べて確認できます(利用枠は消費しません):

[0:07]

皆さんこんにちは、Crust of Rustへようこそ。今回は、一時間半から二時間ほどで扱うには少し欲張りすぎたかもしれないと思っています。録画を後でご覧になっている頃には、成功したかどうか分かるでしょう。今回扱いたかったのは…トレイトと動的・静的ディスパッチ、サイズトレイト、つまりワイドポインタやファットポインタに関する、半ば関連した話題のまとまりです。

Hello folks, welcome back to yet another Crust of Rust. This one, I'm hoping I didn't bite off too much to cover in like an hour and a half to two hours. I guess by the time you watch this recording afterwards, you'll see whether I succeeded or not. So for this one, what I wanted to cover was... a sort of chunk of semi-related topics around traits and dynamic and static dispatch, the size trait, like wide or fat pointers.

[0:44]

そしてVテーブルやコヒーレンスといった事柄も、どれも動的と静的というこの二つのアプローチを持っています。これらはすべて、程度の差はあれ結びついています。それぞれについて多くの質問を受けます。なので、これらすべてがどう動き、どう組み合わさるのかを一つの配信で話そうと思いました。どれか一つの深みにはまりすぎないことを願っています。できるだけ実用的な詳細の範囲で、大部分を扱おうと思います。

And some of the things around like V tables, coherence, they all have this kind of dynamic and static approach to them. They're all sort of tied together, some more so than others. And I get a lot of questions about each one. And I figured I should just do one stream where we talk through how all of this stuff works and how it fits together. I'm hoping that we don't... end up too far down any one rat hole. I think what I'll try to do is cover most of it in sort of workable detail.

[1:18]

そして後日の配信で、そのうちの一つをじっくり掘り下げるかもしれません。ただ、時間内に収めるために、いくつかの詳細は飛ばすかもしれませんが、それで大丈夫だといいなと思います。今回まずはThe Rust Bookから始めたいと思いました。The Rust Bookにはジェネリック型とトレイトとライフタイムについての章があります。その中に、ジェネリクスを使ったコードのパフォーマンスについての小節があります。これは、もしこの本を読んだことがあれば——まだならぜひ読むことを強くお勧めしますが——魔法のように聞こえたかもしれません。

And then we might do sort of a deep dive on one of them in some later stream. But in order to try to contain it to the time, you might find that I skip over some of the detail, and hopefully that'll be OK. So I actually wanted to start this time on The Rust Book. So The Rust Book has a chapter on generic types and traits and lifetimes. And there's this one subsection in there on the performance of code using generics. And this is a section that, if you've read the book, and I highly recommend you do if you haven't already, might have struck you as, you might have read it and be like, that sounds like magic.

[0:07] 皆さんこんにちは、Crust of Rustへようこそ。今回は、一時間半から二時間ほどで扱うには少し欲張りすぎたかもしれないと思っています。録画を後でご覧になっている頃には、成功したかどうか分かるでしょう。今回扱いたかったのは…トレイトと動的・静的ディスパッチ、サイズトレイト、つまりワイドポインタやファットポインタに関する、半ば関連した話題のまとまりです。

[0:44] そしてVテーブルやコヒーレンスといった事柄も、どれも動的と静的というこの二つのアプローチを持っています。これらはすべて、程度の差はあれ結びついています。それぞれについて多くの質問を受けます。なので、これらすべてがどう動き、どう組み合わさるのかを一つの配信で話そうと思いました。どれか一つの深みにはまりすぎないことを願っています。できるだけ実用的な詳細の範囲で、大部分を扱おうと思います。

[1:18] そして後日の配信で、そのうちの一つをじっくり掘り下げるかもしれません。ただ、時間内に収めるために、いくつかの詳細は飛ばすかもしれませんが、それで大丈夫だといいなと思います。今回まずはThe Rust Bookから始めたいと思いました。The Rust Bookにはジェネリック型とトレイトとライフタイムについての章があります。その中に、ジェネリクスを使ったコードのパフォーマンスについての小節があります。これは、もしこの本を読んだことがあれば——まだならぜひ読むことを強くお勧めしますが——魔法のように聞こえたかもしれません。

[1:59] そしてある意味で、このストリームの目的はその魔法を分解し、中身がどうなっているのかを解き明かすことです。特に、単相化という考え方について話します。単相化とは、テキストにあるように、コンパイル時に使われる具体的な型を埋めることで、ジェネリックなコードを特定のコードに変換するプロセスです。しかし、それは少し抽象的です。なので、もう少し具体的な例を取り上げ、そこから進めていきましょう。new libでいきましょう。

[2:34] これをこう呼ぶことにします。うーん、命名は難しいですね。名前はどうでもいいのですが、制約がない分さらに難しくなります。ノルウェー語で書かれた例にしましょう。よし、このテストは消しましょう。

[3:06] テストは必要ありません。では、関数greaterがあるとしましょう。これはTに対してジェネリックです。いや、もっとシンプルにしましょう。関数strlenがあるとします。これはASRF strを実装するものなら何でも受け取り、use sizeを返します。なので、as ref lenとします。

[3:39] とてもシンプルな関数です。少し大きくしましょう。これはジェネリック関数です。sがs ref stirを実装するとして、sはs to use sizeと書いても同じです。この二つは等価です。s ref lenです。そして、コンパイラが文句を言わないように、これらをpubにしましょう。

[4:12] なので、この二つは等価です。完全に等価ではありませんが、同じことをします。そして両方ともジェネリック関数です。これが言っているように、starへの参照に変換できる任意の型を受け取ることができ、このトレイト境界がするのと同じです。そして何が起こるかというと、任意の関数、例えばfooを書き、それがhello worldのstrlenを呼び、さらにhello worldから作ったstringのstrlenも呼ぶとします。

[4:53] ノルウェー語で。これは例を選ぶのに便利なショートカットです。なぜこれらが違うのかを見るために、これはstatic str型を渡しています。これはstring型を渡しています。わお。ですよね?ここでこの関数のポイントに入ります。この関数はジェネリックです。単に文字列参照を受け取るだけではありません。

[5:25] 文字列参照に変換できる任意の型を受け取ります。例えばstringはas ref strを実装しています。なぜなら、stringへの参照があれば、strへの参照を簡単に得られるからです。stringの内部表現はstrだからです。ですよね?ここでジェネリクスがなぜ有用かがすぐにわかります。それは、より柔軟で人間工学的な方法で特定の関数を呼び出せるようにするからです。そして舞台裏で何が起こるか、これがRustの本が単相化について話すときに言っていることですが、コンパイラは実際にこの関数のコピーを二つ生成します。

[6:08] これらの型それぞれに一つずつです。つまりコンパイル時に実際に出来上がるのは、スターリング参照のスティアのようなもので、実際にスティアを受け取ってスタッド・レンを呼び出します。そして最終的に出来上がるのはスターリング文字列で、文字列を受け取って同じことを行います。つまり、この一つのジェネリック定義がコンパイラによってこれらの複数の非ジェネリック実装に変換されるのです。

[6:48] これが単相化のプロセスです。そしてこれはRustにおけるジェネリクスの仕組みの鍵となるものです。このプロセスは関数だけでなく、型にも起こります。キーと値に対してジェネリックなハッシュマップがあると想像してください。実際には、構造体全体とそのすべてのメソッドの完全なコピーが、使用される型ごとに一つずつ得られます。呼び出していない型に対してはコピーが生成されないことに注意してください。

[7:18] これはすべての可能な型に対して生成するというものではありません。任意の型に対してオンデマンドで生成されますが、そのオンデマンドはコンパイル時に決定されます。ある型に対してこの関数が必要なコードがあれば、その時点で生成します。型も同じです。ハッシュマップの場合、その型の組み合わせが実際にコードのどこかに現れた場合にのみ、ハッシュマップ型の特定のインスタンスが生成されます。これはまた、Rustのコードをコンパイルして、ライブラリとして使えるバイナリを人々に配布するのが少し難しい理由の一つでもあります。

[7:58] なぜなら、これをバイナリ形式で配布したいRustライブラリに持っていると想像してください。動的リンクライブラリのようなものを考えてください。実際かなり複雑です。なぜなら、Rustは各型に対してこの関数の異なるコピーを生成することになっていますが、元の関数が定義されている元のライブラリとは別の場所で、利用側で定義された型でインスタンス化される可能性があるからです。したがって、それらのインスタンスをすべて生成するにはソースが必要なのです。

[8:31] そして単相化が素晴らしい理由は、潜在的にずっと効率的なコードを生成できるからです。スターリングはここではあまり良い例ではありませんが、もう少し複雑なものを想像してみましょう。実は良い例はHashMapです。ここでHashMapの完全な定義を書き出すつもりはありません。しかしHashMapで最終的に得られるのは、使用する具体的な型ごとに型のコピーが得られるからです。HashMapの一つのインスタンスのキーが…と想像してください。

[9:06] 文字列であり、別のインスタンスではキーが数値である場合、コンパイラがHashMapの各メソッドのコードを生成するとき、たとえば各キー型のハッシュ関数の定義をインライン化するような形で生成されます。つまり、文字列を使うHashMap版のコードでは、文字列をハッシュするコードがHashMapのコードに直接埋め込まれ、その型が文字列であるという事実に基づいてそのコードを最適化できるのです。

[9:40] 同様に、数値のようなものの場合、すべてのジェネリクスを単相化した後、ハッシュが実は数値の値そのものであることに気づくので、ハッシュ化を完全に省略できるかもしれません。それは実際には正しくないかもしれませんが、コンパイラが使用される特定の型に対して具体的に書き出されたコードを見ることができ、それによってはるかに優れた最適化が可能になる、という感覚はつかめるでしょう。より複雑な側面に進む前に、ここまでは理解できましたか?ジェネリクスの一般的な考え方と、単相化がなぜ良いのかについて、理解できましたか?

[10:28] では、チャットで誰かが指摘したように、欠点は、そう、単相化の欠点の一つは、使用されるすべての型に対して型や関数のコピーを生成する必要があるため、バイナリが大きくなることです。単純に型の数を掛けるほど悪くはありません。その理由の一つは、たとえばHashMapの場合、特定の型の組み合わせに対してメソッドの一部しか使わないかもしれないからです。そして、それは生成されません…たとえば、キー型が文字列のHashMapが一度でもあれば、文字列キー型に対するHashMapのすべてのメソッドが生成されるわけではありません。

[11:08] 実際に呼び出すメソッドだけが生成されます。そのため、コストは少し償却されます。しかし、最終的なバイナリのコードが増えるのは事実です。その副作用として、コードが少し非効率になることがあります。つまり、今では、一つのSterlinという関数、つまりコンピュータがジャンプできる一連のアセンブリ、実質的にはマシンコードがあるのではなく、

[11:40] そうすれば、そのマシンコードの行をキャッシュに保持できるので、次回により効率的に実行できます。代わりに得られるのは、二つの異なる関数があり、あるコードは一方にジャンプし、別のコードはもう一方にジャンプし、それらはメモリの別々の領域なので別々にキャッシュする必要があり、命令キャッシュの効率が少し悪くなるという欠点があります。また、コンパイラがこれらのコピーを生成する必要があるという意味で少しコストがかかりますが、通常は非常に多くの型でインスタンス化しない限り、実際にこれらを生成するコストはそれほど大きくありません。

[12:22] ええと、それはRustのバイナリがCのものより大きい主な理由の一つですか?それは少し異なります。Rustのバイナリはより多くのものを静的コンパイルするので、それが理由の一部かもしれません。一部は単相化です。一部は、正確な詳細は忘れましたが、標準ライブラリからより多くのものがコンパイルに含まれることだと思います。そしてもう一つの非常に大きな理由は、Rustがしばしばデバッグシンボルを組み込むことです。

[12:54] それをバイナリから削除しないと、実際のマシンコードはごくわずかでデバッグシンボルが多いバイナリになってしまうので、単にバイナリをストリップしてみるのもよいかもしれません。コンパイラは生成された関数をインライン化しようとしますか?はい、これが単相化が非常に優れている理由の一つです。なぜなら、それが文字列かstrかをインライン化するだけでなく、例えばboolを受け取り、関数であるfを受け取り、option tを返すようなPubFnがあるとします。

[13:42] そして実装が例えば、もしbならsome f、そうでなければ、のようになっているとします。そしてこの関数は実際に標準ライブラリに追加されたばかりですが、boolのメソッドとしてです。ここで、この関数を特定の提供されたクロージャや関数で実行すると、bool thenのコピーが生成され、渡したクロージャのコードがこの関数に直接インライン化されます。そのため、それに応じて最適化できます。

[14:14] ええ、ですからインライン化されます。ここではインライン化という言葉は適切ではありません。それに基づいてインライン化および最適化する選択肢があるのです。必ずしもそうする必要はありません。ただ、特定の型に単相化されるので、その型が正確に何であるかを知っており、望めばインライン化を選べるということで、これは重要な区別です。サイズが大きくなる大きな理由は標準ライブラリです。

[14:44] それは完全に正しいわけではありません。なぜなら、実際に使用する標準ライブラリの部分だけがバイナリに含まれるからです。ただし、標準ライブラリのジェネリクスを多用すると、サイズが大きくなるのは事実です。メソッドの重複によるコストはどれくらいでしょうか?ほぼゼロです。複数の関数を生成すること自体はそれほど重要ではないと思いますが、重要なのは、関数のコピーを多数生成すると、それぞれをマシンコードにコンパイルする必要があり、コンパイルプロセスが遅くなることです。strlen文字列は値渡しの文字列ではなく、参照渡しの文字列を受け取るべきではないでしょうか?

[15:23] 実際にはどちらでも受け取れます。どちらも動作します。これがaskRefStirを受け取るのが良い理由の一つです。動的ライブラリはジェネリクスをどう扱うのでしょうか?扱いません。これはRustライブラリの動的リンク、あるいはRustライブラリをバイナリ形式で配布することさえ困難な理由の一つです。そして、Swiftではこのようなものを安定化させようとしていると思います。

[15:54] Rustでまだどう使うかはよく分かっていません。そして、はい、Cのdilib、つまりRustで多数の外部関数を持つ動的リンクライブラリのようなものには使えません。それらはジェネリックにできません。では、単相化とは何かが分かったところで、ここでの実際のディスパッチのプロセスについて少しお話ししたいと思います。

[16:27] ディスパッチとは... 実際、ストリーム全体でもう少し長く使える、もう少し良い例を挙げましょう。独自のトレイトを定義しましょう。このトレイトを... シンプルにHelloと呼びましょう。いや、ノルウェー語の挨拶にしましょう。メソッドを一つだけ持ちます。

[17:00] そして、実際には何も返さず、ノルウェー語で挨拶するだけの単一の関数としてシンボルを持つとしましょう。そして、例えばstrに対してこのトレイトを実装すると想像できます。ええと、それがするのはprint line、あ、self、おっと。ええと、そして、あ、Jドットにしましょう。

[17:40] こんにちは。ああ、今日はタイプできない。ここで舞台裏で起こっているのは、コンパイラがこのコードを生成しようとするとき、この型を決定し、次にstr参照型で利用可能なメソッドを調べます。highという名前のメソッドは見つかりません。そして、スコープ内のトレイトを調べ、レシーバ型に対して実装されているhighメソッドがあることを見つけます。

[18:18] そして結局、それを呼び出すことになります。問題なさそうです。では、これの汎用的なバージョンがあるとしましょう。highを実装した何かを受け取り、おそらくhとします。そして単にh.highを呼び出すだけです。これはより厄介ですよね?コンパイラがこのマシンコードを生成するとき、何らかの方法でこのメソッドを呼び出す必要がありますが、Hの型を実際には知りません。ここで単相化の出番ですよね?

[18:51] 実際に生成されるのは、H、B、strを持つbar strです。そしてこれをディスパッチし、ここで何を呼ぶかを判断するのは簡単です。なぜなら具体的な型がわかっているからです。これが静的ディスパッチと呼ばれるものです。つまり、コンパイル時にコンパイラは実際の型を知っています。したがって、このメソッドを呼び出そうとするとき、これがこのメソッドであることがわかります。

[19:22] そして単にジャンプできます。基本的にこれはアセンブリコードでの呼び出しになり、メモリ内の既知の位置にあるこの関数を呼び出しますよね?なぜならそれがこのメソッドのある場所だからです。静的ディスパッチについて理解できましたか?このメソッドを生成できれば、このコードをどうコンパイルするかを判断するのは簡単になります。なぜならこのメソッドはこれと同じだからです。そしてどちらもhighメソッドがどこにあるかを判断するのは簡単です。

[20:05] さて、この静的ディスパッチを見てきたので、では代替手段は何だろうと思われるかもしれません。これに対して多数の異なるコピーを生成したくない場合はどうでしょう?ここで動的サイズ型に戻ります。ああ、すみません、はい、ここのimpl highは単なるジェネリクスの糖衣構文です。これは等価です。以前スターリングで示したように、これはHがhighであることと等価です。

[20:40] この二つは等価です。では代替手段は何でしょう?この単相化は望まない、複数のコピーも望まない。あるいは、これを想像するもう一つの理由として、highを実装したもののベクタが欲しいとしましょう。ここのfooで、これのベクタを持ちたいのです。

[21:21] そしてこのベクタ内のhに対してh.highを呼び出したいのです。それらがすべて同じ型なら問題ありません。しかし、highであるもののコレクションやシーケンスやセットが欲しくて、実際に同じ型である必要はない場合はどうでしょう?気にするのは、これがこのトレイトを実装していることだけです。より具体的には、barを書きたいとして、impl highのスライスであるような何かを受け取りたいとします。

[22:02] このバージョンから始めましょう。では、s内のHについて、h.highです。これは問題なく動作します。barを、例えばaのようなもので呼び出せます。問題なく動作し、問題なくコンパイルされます。同様に、それぞれを文字列に変換することもできます。それも問題なく動作します。

[22:40] ああ、そうか、string用にこれを実装していませんでした。でもこれは問題なく動作します。しかし、例えばこんな風に呼び出せるようにしたいと想像してみましょう。これは本当は問題ないはずです。でもそれはできませんよね?異なる型のものを集めたベクターは作れません。そもそもそんなものは作れないのです。でも今回の場合、具体的な型が何であるかは実際には気にしていません。

[23:11] これらが文字列であることは気にしていません。気にしているのは、それらがheightトレイトを実装しているという事実だけです。それだけが重要なのです。だから、具体的な型を気にせずに、この振る舞いを持つもののベクターを作れるはずです。ここで動的ディスパッチとトレイトオブジェクトの領域に入ります。本にもこれについての章があります。どこにあるか探しましょう。間違った順番で開いてしまいました。私の愚かさですね。

[23:50] あちこち飛んでしまってすみません。ここ、この章の下の方にあります。本にはかなり良い章があり、異なる具体的な型のものを同じ型として扱う能力について説明しています。彼らが使っている別の例としては、GUIの場合、描画可能なもの、つまりdrawトレイトを実装したものがたくさんあるかもしれません。そして、単にリストやイテレータを受け取るdraw関数のようなものを持ちたいと思うかもしれません。

[24:25] 描画するすべてのものの。そして、そのうちのいくつかはボタンかもしれず、いくつかは画像かもしれず、いくつかはテキストボックスかもしれませんが、draw関数にとっては実際には関係ありません。気にしているのは、描画可能なもののイテレータを受け取るということだけです。これは、highを呼び出せるもののスライスを受け取りたいという、これと似たような感じですよね。そして必要なのは、トレイトオブジェクトとして知られるものです。トレイトオブジェクトとは、dynキーワードが見られるものです。

[24:58] これは実際にはコンパイルされません。なので、私がやろうとしているのは、これが私が欲しいもののようなものですよね。implは、覚えておいてください、これは省略形です。そして、ここで実際に型を書き出すのが役立ちます。これはこの省略形です。そしてこれは何が起こっているかの手がかりを与えてくれます。barは一つの型に対してジェネリックで、その型はstr参照かstringのどちらかでなければなりません。両方はできません。なぜなら一つの型に対してのみジェネリックだからです。そして、ここにH2 highのようなものがあると想像できますが、スライスやイテレータを受け取っていることを考えると、h2を置く場所がありません。

[25:38] イテレータは一つだけで、そのイテレータは一種類の型の要素しか持っていません。なので、これは実際にはうまくいきません。ある意味で言いたいのは、それぞれのものがハイであるということです。他に気にしている具体的な型はありません。そして実際、これを書くとコンパイラエラーが出て、新しい画面でこれを出してみましょう。『明示的な dyn のないトレイトオブジェクトは非推奨です』と表示されます。

[26:10] では、まず警告を取り除きましょう。ここに dyn を入れる必要があると言っているので、そうします。すると今度は『dyn ハイ型の値のサイズはコンパイル時に知ることができません』と表示されます。これはこの部分を指して、『コンパイル時にサイズが分かりません。トレイト Sized は dyn ハイに対して実装されていません。スライスと配列の要素はサイズ付きの型でなければなりません』と言っています。これは以前に見たことがあるかもしれないエラーです。そして、このストリームの残りの一部で話すことの一つは、なぜこのエラーが出るのか、それが何を意味するのか、修正方法は何か、Sized とは何か、そしてこれが動的ディスパッチやトレイトオブジェクトとどう関係するのか、ということです。

[26:50] ここで少し止めましょう。たくさんのことを一度に話してしまったので。意味が通じるか見てみましょう。ダークモードとライトモードについての議論がたくさんありました。本当に言いたいのは、これを一種の型消去と考えることができるということです。あるコレクションを取りたい、そしてそのコレクションがこのトレイトを実装しているということだけを気にしている、と言いたいのです。

[27:26] このトレイトの抽象的な概念を取りたいのです。さて、コンパイラが指摘している課題は、この場合、そもそもどこから始めればいいのかということです。まず Sized について話す必要があると思います。では Sized トレイトを見てみましょう。Sized トレイトにはメソッドがありません。マーカートレイトです。

[27:58] それがマーカーモジュールにあるものです。説明には『コンパイル時にサイズが分かっている定数サイズの型』とだけ書かれています。さて、ほとんどの型は Sized です。例えば構造体 foo を作ると、それはおそらく Sized です。標準ライブラリのほとんどの型は Sized です。実際、Sized でない型はごくわずかです。ごくわずかなので、すべてのトレイト境界には、たとえ foo T のようなものでも、その型が Sized であることを要求する暗黙の境界があります。

[28:32] その理由を見るために、何が起こるか考えてみましょう。これを少しコメントアウトして、少しコメントアウトして。もっと賢くできると思います。最初のとてもシンプルな strlen の例に戻りましょう。

[29:05] これは、アスタリスクstrを実装する何らかのSに対してジェネリックになります。そのSを受け取ります。そしてuSizeを参照長として返します。つまり、何かがstrlenを呼び出したいとします。strlenはそのsである引数を受け取ります。なので、何かを渡す必要があります。何らかの方法でその引数を渡す必要があります。渡される引数はスタック上にスペースを取るか、レジスタで渡されるか、どちらかです。

[29:41] これはつまり、コンパイラが結果のアセンブリに、この引数が何であれ必要なスタック上のスペースを確保するコードがあることを確認する必要があるということです。そしてそれにはコンパイラが引数の大きさを知っている必要があります。ここでのsは、具体的な実装を考えると、strlen strですね。ここでは、これはただの、うーん。

[30:20] そして文字列の実装で行きましょう。つまり文字列は本当にただ、二つの数値とポインタですよね?文字列の長さ、割り当てのサイズ、そしてヒープ上の実際の文字列の最初の文字へのポインタです。つまりそのサイズです。コンパイラはこの引数のサイズが三ワード、三つであることを知っています。いわゆるuseサイズですよね。

[30:52] なので、この関数のアセンブリコードとこの関数の呼び出しのアセンブリコードを簡単に生成できます。引数がどれだけのスペースを取るか知っているからです。同様のことを想像できますよね。もし戻り値の型に対してジェネリックだったら、スタック上で戻り値の型に実際にどれだけのスペースを割り当てるか知る必要があります。なので、ここでsがサイズ付きであると特に言っていなくても、基本的に常に型がサイズ付きであることが要件です。そうでなければ、コンパイラは必要なコードを生成する方法を知らないからです。そうです。

[31:35] わかりました。ではなぜ。なぜこれを使おうとしているときにコンパイルできるのでしょうか?実は、din highはhighを実装するもの、つまり具体的な値を与えずにhighを生成するものと言っているだけです。思い出してください、これを文字列やスターやその他のこのトレイトを実装するかもしれない型のスライスにしたいのです。そしてそれらはすべて異なるサイズですよね?文字列は二つの数値とポインタ、strは一つの数値とポインタ、そして構造体としてギガバイトの大きさの型fooがあると想像できますよね?

[32:16] そして、それに対してhiを実装します。これもここで渡すべきものかもしれません。つまり、このスライスにはサイズがありません。スライスは本当にただの連続したメモリ領域にすぎませんよね?各チャンクが同じサイズである必要があります。すべてが同じサイズの配列です。しかし、それらのサイズがわからなければ、同じサイズであることを保証できません。もし私があなたにこれらの一つを渡したら、ここでのdin highはサイズ指定されていませんよね?

[32:47] なぜなら、それはonce high以外の任意の型であり得て、任意のサイズになり得るからです。そして私があなたに「四番目の要素をください」と尋ねたとします。通常、配列ではすべての要素が同じサイズなので、四番目の要素は先頭へのポインタに一要素のサイズの三倍を足したものにすぎませんよね?これが四番目の要素に到達するためのポインタ演算です。しかし、それらが異なるサイズなら、そのコードを生成できません。だからこそ「スライスと配列の要素はサイズ型を持たなければならない」と言っているのです。そうでなければ、その型は意味をなしません。

[33:23] では、どうすればこれを修正できるでしょうか?私たちは本当にこれをできるようにしたいのです。Rustがトレイトを実装するものをコレクションとして扱う能力を提供しないなんて、正気の沙汰ではありません。そして配列だけがここでの問題ではありませんよね?たとえ私たちが、これの良い例は何だろう、例えばdin asref strを受け取るstrlen2があったとしましょう。同じ問題がありますよね?

[33:57] これをコンパイルしようとすると、同じことが表示されます。他のメッセージを消しましょう。すると「din sRF str型の値のサイズはコンパイル時に知ることができません。Sizedはdin as refに対して実装されていません。関数の引数は静的に既知のサイズを持たなければなりません。借用型は常に既知のサイズを持ちます」と表示されます。そして修正方法の提案をしてくれます。しかしこれがまた重要な洞察です。コンパイラは引数の型がどれくらいの大きさかを知る必要があるのです。

[34:31] そうでなければ、関数呼び出しのコードを生成できません。つまりこれは、これらの型がサイズ指定されているというコンパイラの根本的な要件のようなものです。ここまでで意味は通じますか?なぜこれが問題なのか、という点について。Sizedの実装を見せてもらえますか?Sizedは、それを実装できる任意の型に対して自動的に実装されます。

[35:04] つまり、フィールドのないstruct fooのようなものを書くと、それはサイズ指定されています。そこにstringを追加すると、stringはサイズ指定されているので、fooもサイズ指定されます。さらにboolを追加しても、この型は依然としてサイズ指定されています。型は可能であれば常にサイズ指定されます。例外は、私が次のようなことをした場合です…そして実際、これがtを保持する代わりにfoo tを書いても、すべてのトレイト境界にはサイズ指定されているという暗黙の要件があることを覚えておいてください。だから依然としてサイズ指定されています。

[35:38] つまり、ここには暗黙のうちにサイズ付きという性質があるわけです。ということは、Tはサイズ付きです。だからすべてのフィールドがサイズ付きです。したがって、fooはどのTに対してもサイズ付きです。なので、自分でSizedを実装することは決してありません。それは常に自動トレイトとしてのみ使われます。問題はスタックサイズではありません。

[36:12] 問題は、スタックに収まらないかもしれないということではありません。関数を呼び出すには、そう、ちょうどマシンコードの層で、あるいはアセンブリの層と考えてもいいですが、関数を呼び出すには、その関数を呼び出すときに、その関数のスタック変数用にどれだけの領域を確保するかを知る必要があるのです。その引数の一部を含めるかもしれませんし、呼び出し側で、戻り値のための領域を確保しなければならないとき、その領域はどれくらいの大きさであるべきでしょうか。根本的には、それは単に領域の大きさを知る必要があるということであり、なぜならそのスタックを作るためのマシンコードを生成できないからです。

[36:49] ずるい方法もありますが、基本的にコンパイラは効率的なコードを生成するために、これらのもののサイズを知らなければなりません。さて、サイズ付きでないものは何でしょうか。トレイトについてはすでに話しました。これは、pub fn fooと書いて、単に引数としてimpl Traitを取るとします。

[37:27] ここでのTraitはトレイトであり、多くのものがそのトレイトを実装しており、それらはすべて異なるサイズかもしれません。したがって、これは定義されたサイズを持ちません。ここでimplと書くと、implはimpl Traitの省略形です。このimpl Traitはサイズ付きです。なぜなら、具体的な型ごとにfooのコピーが得られるからです。そして、それらのコピーのそれぞれについて、その型のサイズは既知です。ここで単相化のために静的ディスパッチを使えば、これは問題ありません。

[37:59] しかし、単にトレイトそのものを取ろうとして、基本的にこの関数はトレイトを実装するものなら何でも受け取るとすると、これはサイズ付きでないため動作しません。そしてこれはdyn Traitと書くのと同等です。これはサイズ付きではありません。このようなものをどうやってサイズ付きにするかについては、すぐ後で話します。ええと、もう一つの例は、ええと、私の構造体fooに戻ると、ええと、それにStringを保持させようとすると、ええと、Stringはサイズ付きではありません。ええと、なぜなら文字列はある意味どんなサイズにもなり得るからです。文字列へのポインタではなく、文字列そのものについて考えると、どんなサイズにもなり得ます。ええと、同じことが、ええと、これ、参照なしのスライスのようなものも同様で、要素がいくつあるかわからないため、サイズ付きではありません。

[38:51] したがって、明確に定義されたサイズを持ちません。これらが、サイズ付きでないものについて私が知っている最良の二つの例です。そして、次にそれらの型を含むものはすべて同様です。チャットでは、これから説明しようとしていること、つまりこれをどう修正するか、なぜ参照が必要なのかなどについて説明しようとする議論がたくさんあります。約束します、そこまで話します。

[39:28] はい、結構です。では、ここまでで大体話が通じていると思います。では次に、この状況をどう解決するかという問題になります。ここでSterling 2、まあSterling Dinと呼びましょうか。これをモノモルフィズされないようなメソッドで扱いたいわけです。しかしこれはサイズ付きではありません。ではどうすればよいでしょうか。ここでのコツは、これを常にサイズ付きとなる型にすることです。

[40:05] そしてその方法は、任意の内部型に対してそれ自体がサイズ付きであるような型を介して間接化することです。その例が参照です。参照は常に同じサイズで、ポインタ一つのサイズ、場合によってはポインタ二つ分になりますが、それは後ほど説明します。これはサイズを持っています。コンパイラは、後に続く型が何であっても、このサイズがどれだけかを常に知っています。これは単なるポインタだからです。

[40:40] 同じことはボックスでも言えます。ボックスもまた、ヒープへの単なるポインタです。こうすれば、この引数のサイズは既知となり、問題ありません。そして実際、何かをモノモルフィズせずにトレイトそのものを扱う方法は、何らかのポインタ型の背後に置くことです。参照やボックス、アークのようなものです。

[41:13] 実際にこれがどう動くかというと、ボックスの定義を見ると、そこには魔法が込められています。魔法ではありませんが、いろいろなものが入っています。基本的には単なるポインタです。完全に正確ではありませんが、ほぼそう言えます。ボックスには実際にこの定義があります。ここでの疑問符は「そうである必要はない」という意味です。つまり、すべてはサイズ付きでなければならないという自動的に追加される境界からオプトアウトして、ボックスではTはサイズ付きである必要はないと述べているわけです。

[41:50] だからこそ、それ自体がサイズ付きでないもののボックスを作れるのです。これがうまくいく理由は、最初にボックスを作るとき、ボックスに入れようとしているもののサイズ分の割り当てを行うからです。これを例示するために、ここでmainを書きましょう。ある時点で、例えばhelloから作った文字列のボックスnewを行う必要があります。

[42:25] そうでしょう。そして今度はこれがdin as ref strになると言えます。これはxと言うべきで、こちらはstrと言うべきです。そしてyでstrlen dinを呼び出せます。つまり、ボックスを作った時点で、具体的な型を持つ何かを渡さなければならなかったのです。そしてその時点で、その型のための領域をヒープ上に割り当てたのです。

[42:57] しかし、ボックスは単なるポインタなので、サイズは依然として既知です。これをこのためのボックスに変換しても、概念上は依然として単なるポインタです。たとえそれが指すもののサイズが任意であってもです。しかし、この関数に渡す実際の引数にはサイズがあるため、関連するコードを生成できます。このように、間接参照の型のサイズが既知である型を介した間接参照がなぜ機能するのか、お分かりになりますか?理屈は通っていますか?

[43:37] トレイトの組み合わせについてもお話しします。そうですね。複数のトレイトについては必ず触れますと約束します。BoxedInAsteroidStir を直接 X に置くことはできないのですか?ええ、そうすればこれもできます。AsteroidStir です。それも問題ありません。しかしそれでも、Box New にはサイズが既知の具体的な型を提供する必要がありました。

[44:16] ボックスは参照よりもいつ使うべきですか?つまり、これをこれよりもいつ選ぶのですか?それについて厳格な決まりはありません。一般に、ボックスの利点は静的であることです。したがって、呼び出し元のスタックフレームがなくなった後でも使い続けられます。つまり、通常ボックスを参照よりもいつ選ぶかと同じことです。では、関数にスタックへの参照を渡すこともできますか?ええ、まさにその通りです。

[44:47] ですから、ここでもできます。ここでやってみましょう。ですから、完全に可能です。そして Sterlendyn、なぜでしょう?その通りです。ですから、これは、din2 がこれを受け取り、これが din2 を呼び出せる、としましょう。

[45:25] なぜこれが文句を言うのでしょうか?ボックスにもアスタリスクメソッドがあるからです。だから二重アスタリスクが必要なのです。ええ、ご覧のとおり、スタック上にあるものについても同じことができます。ここでポインタを介して間接参照するようなものを作り、それを参照を受け取るものに渡すことができます。

[45:59] そして実際、これもできると思います。ええ、問題ありません。なぜこれが機能しないのかはそれほど重要ではありません。さて、私たちが今構築したものは TraitObject として知られています。それは、トレイトを表すという性質だけを持つオブジェクトです。これが TraitObject です。それらは、何らかの基盤となるトレイトとしてのみ振る舞うものです。

[46:35] これは TraitObject であり、これも TraitObject です。ラップしている型が何であるかは関係ありません。ボックスは一種のポインタ型です。ええ、ボックスはポインタ型です。トレイトオブジェクトを元の具体的な型に変換できますか?答えはノーと言いたいところですが、技術的には時々可能です。しかし一般にはノーです。これは本質的に型消去と考えることができます。

[47:08] 技術的には、安全でないトランスミュートなどを通じて戻ることは可能ですが、一般的には、トレイトオブジェクトに変換した瞬間に、それが以前どの型だったかという知識は消去されます。しかし、安全でないものやanyトレイトの周りには使える魔法がいくつかあります。ただし、一般的にはそれは無視すべきです。また、これを行うと、このトレイトを使用する能力だけが保持されることに注意してください。具体的な型が何であったかに関する他のすべての知識は消去されます。

[47:39] つまり、ボックス化されたASRFトレイトに対してできるのは、それに対してASRFを呼び出すことだけであり、他には何もできません。ここでも同じです。そして、その理由についてはすぐに説明します。さて、これで興味深い疑問が生じます。例を挙げましょう。これを二番目に、これを一番目にして、これらを入れ替えてもまだコンパイルできるようにします。次に、コンパイラがこの関数のマシンコードを生成しなければならないときに実際に何が起こるかを考えてみましょう。

[48:15] ある時点で、実際にコンパイルを行い、実行可能なマシンコードに変換できるアセンブリコードを生成する必要があります。つまり、ここでのSはSrefを実装する何らかの型です。実際、私たちのhighトレイトに戻りましょう。その方が少し良くなります。では、ここに戻って、dinHiを受け取り、何も返さず、単にHiを呼び出すsayHiが欲しいとしましょう。そうですね。これは、Hiトレイトのトレイトオブジェクトを受け取ります。しかし、コンパイラがここでコードを生成するとき、sがどの型であるかはわかりません。ですよね?

[49:01] それは単なるトレイトオブジェクトです。実際には単なるポインタです。では、どのようにhighメソッドを呼び出すのでしょうか?覚えているように、ジェネリックの場合、静的Hです。この場合、実際には各具体的な型に対してこれのコピーを取得します。

[49:37] つまり、実際にはこれはこれに変わります。そして、この具体的な実装では、マシンコードの生成は簡単です。なぜなら、これは実際には何かへのアセンブリ呼び出しのようなもので、この行、行6への呼び出しです。実際には行ではなく、バイナリ内のメモリ位置ですが、お分かりいただけるでしょう。コンパイラはコンパイル時に静的にどこへ行くべきかを知っています。

[50:10] しかし、動的な場合、何を呼び出すのでしょうか?これがstrなのかStringなのかはわかりませんよね?ですから、これのアドレスを生成すべきか、これのアドレスを生成すべきか、それとも全く別の何かのアドレスを生成すべきかはわかりません。では、これはどのようなマシンコードに変わるのでしょうか?ここで動的ディスパッチとVテーブル、つまり仮想ディスパッチテーブルの出番です。トレイトオブジェクトを構築するためのトリックは、ボックスの参照が単に一つのポインタ幅であるというのは実は完全には真実ではないということです。

[50:48] 実は、指し示されている型について少しだけ余分な情報を持っています。ではここで、Rustの本に戻りましょう。Rustの本には、動的サイズ型とsizeトレイトについての章があります。これは高度な型の章にあります。そしてそこで語られているのは、実のところ、私たちがここで話したかったほどには語っていません。ここでは。

[51:22] 代わりにRustリファレンスを使いましょう。動的サイズ型に関するRustリファレンスにはこうあります。ほとんどの型はコンパイル時に知られる固定サイズを持ち、私たちが話してきたようにsizedトレイトを実装します。サイズが実行時にのみ知られる型は動的サイズ型、あるいは非公式にunsized型と呼ばれます。そして、スライスとトレイトオブジェクトが動的サイズ型の二つの例です。これが実行時にのみ知られる理由は、コンパイル時にはこの型が何になるか分からないからです。分かるのは実行時になってからです。

[51:54] そして、もう少し具体的にするために、main関数があって、もしrand、乱数は持っていませんが、randomがfourだとします。もしrandomがfourなら、これのsay hiを呼び、そうでなければworldからの文字列のsay hiを呼ぶ、と想像してみてください。いいですか?

[52:30] そして、randomが4よりもランダムだったと想像してみましょう。実行時まで分かりません。これがユーザーから読み取られたものだとしましょう。コンパイル時には、ここでどの実際の型が使われるか分かりません。コンパイル時に予測できない何らかの入力によって、実行時にのみ決定されます。いいですか?だからこれが実行時に決定されるのです。そしてこうあります。動的サイズ型へのポインタ型はsizedですが、sized型へのポインタの二倍のサイズを持ちます。

[53:09] つまり、トレイトオブジェクトへのポインタはVテーブルへのポインタも格納します。ここでVテーブルとは何かという話に入ります。トレイトオブジェクトがあるとき、例えばdyn piのようなものでは、参照に実際に格納されるのは、一つ目は実際の具体的な実装型へのポインタ、二つ目は参照されたトレイトのVテーブルへのポインタです。

[53:48] ではVテーブルとは何でしょうか。Vテーブル、すなわち仮想ディスパッチテーブルは、その型のトレイトの各メソッドへのポインタを持つ小さなデータ構造です。highトレイトの具体的なケースでは、例えばdyn highがあるとすると、Vテーブルは、highというメンバーを一つだけ持つhigh Vテーブル構造体のようなものだと考えることができます。それはFnへのポインタで、そのFn自体はTが何であれそのポインタを取ります。

[54:45] つまり基本的に、トレイトオブジェクトに変換される具体的な型ごとに、異なるVテーブルが構築されることになります。ですから、例えばstrから始めてdyn Highにしたい場合、実際に構築されるのは、例えば、ええと、まず一つ目はstrへのポインタになります。

[55:16] そして二つ目はHighのVテーブル、つまりhighがstr as high、highであるものへのポインタになります。この変換を行うとき、コンパイラはこのVテーブルを構築しなければならないことを認識しており、そのVテーブルのアドレスをその参照の中に格納します。

[55:48] つまり、この参照には二つのものが含まれています。実際の型へのポインタと、この特定の変換の際にコンパイラが生成したVテーブルへのポインタです。ですから、トレイトオブジェクトに変換される型ごとに、そのようなVテーブルが一つずつ存在することになります。そして今、コンパイラがこのコードを生成しようとすると、実際に生成されるのはs.VTable.High s.Pointerのようなものです。

[56:23] そして、もし誰かが例えば文字列を渡した場合、それは異なるVテーブルを持つことになります。つまりs.Vtableは異なるポインタになります。この場合、これはstr highはどこか?例えば6行目ですよね?つまりこれは6行目へのポインタになります。しかし代わりに、質問はすぐに受け付けます。もしこれが代わりに文字列からdyn highへ行く場合、それは文字列へのポインタとstring as high、つまり12行目にあるこのメソッドになります。

[57:06] 言い換えれば、生成されるこのコードは、どの型が渡されても機能します。なぜなら、Vテーブルを介して間接参照し、各型がそれぞれ独自のVテーブルを持っているからです。さて、一度にたくさんのことをお伝えしましたが、あまりひどくなかったことを願っています。では見てみましょう。

[57:45] Vテーブル自体はコンパイル時に静的に構築されるのでしょうか、それとも動的に割り当てられるのでしょうか?Vテーブルは…Vテーブルはコンパイル時に構築され、静的に構築されます。そして一般に、二つ目の部分は…つまりこれはファットポインタまたはワイドポインタと呼ばれるもので、一つのポインタではなく二つのポインタを含んでいるからです。ですからこれを見るたびに、実際にはワイドポインタです。そして一般に、そこにある二つ目のポインタは常に静的に知られています。なぜなら、元の構築によって決定されるからです。

[58:23] トレイトオブジェクトの。一般にと言ったのは、技術的にはオンザフライで構築することもできるからです。ここでの呼び出しには、静的に知られていることを要求するものは何もありません。ですから、手動でvtableを構築することを想像できます。そしてこれは使われており、それについては後でもう少し詳しく話します。Refsterは文字列スライスの長さも含んでいます。

[58:56] はい。つまり一般的には、実際にはこうなります。ですからこれは実際の文字列へのポインタではありません。実際には str 参照へのポインタであり、その参照自体が長さを保持しています。Vtable 構造体を何とかしてデバッグ出力できますか? コンパイラに Vtable 構造体を出力させる方法は知りませんが、基本的にはこれだけです。

[59:33] これは単に、これがトレイトオブジェクトである対応するトレイトの各メソッドごとにメンバーがあり、各メンバーは… 各メンバーは対応するメソッドであり、その値はその具象型に対するそのメソッドの実装へのポインタです。では、self を取らないトレイト関数がオブジェクト安全でないのはなぜですか? コンパイラが self を使わない fn mute self を生成するだけではだめなのでしょうか?

[1:00:08] それについてはすぐに話します。インスタンスを作成するたびに新しい V テーブルを構築するのでしょうか? いいえ、V テーブルは一般にその型に対して静的に構築されます。動的に構築されることはありません。同一の V テーブルは検出されますか? いいえ、これらの重複排除は行われません。実際、それらは重複しないことが保証されています。

[1:00:43] 二つの異なる型に対してトレイトを実装すると、たとえ実装が同じコードを含んでいても、ソースコード内および結果のバイナリ内で依然として別々の場所であり、したがって異なるアドレスを持つことになります。複数のトレイトのトレイトオブジェクトについてはすぐに説明します。つまり box dyn は、オブジェクトを指すワイドポインタを指すシンポインタです。いいえ、box dyn height がある場合、その box 自体がワイドポインタです。

[1:01:22] つまり box は少し特殊な型です。実際にはそれほど特殊ではありません。単に box が内部的に mute dyn hi を含んでいるだけです。そして Rust コンパイラは参照とポインタについて、それらがトレイトオブジェクトであれば実際には幅 2 であることを知っています。ですから box は特殊ではなく、ポインタ型が特殊なのです。つまり box.dynhi 自体がワイドです。余分な間接参照が生じることはありません。はい、トレイトオブジェクトのナイトリー API についても話します。

[1:02:13] では、これで大体意味が通る段階に来たと思います。トレイトオブジェクトが完全にジェネリックであるよりも少し制約が多い理由がいくつかあります。例えば、dyn hi + sref stir である s を取る hubfn baz を持ちたいと想像してみましょう。

[1:02:58] そして s.hi を行います。さらに、let S is S dot S ref と言い、その後再び S dot high を行います。なぜなら文字列自体が high を実装していることを知っているからです。これは混乱を招くかもしれません。単に len にしたほうがよいでしょう。ここでコンパイラは、ああ、曖昧だと言いました。では曖昧さを取り除きましょう。それは議論にはあまり関係ありません。

[1:03:33] まだやらせてくれない、なぜだろう?もしかして曖昧さをなくすためにこれをやる必要があるのかな?いや、いいや、ちょっとここで文法がうまくいったふりをしてみよう。つまり、二つの異なるトレイトのトレイトオブジェクトが欲しいと言いたいわけだ。これは実際にはコンパイルできないし、パースエラーはちょっと置いておいて、これが動かないもっと大きな理由がある。それが動くためには、highメソッドがどこにあり、asrefメソッドがどこにあるかを両方知る必要があるんだ。

[1:04:18] でもそれらは二つの異なるvtableに含まれている。一つは具象型のhigh用のvtableで、もう一つは具象型のasref用のvtableだ。だから実際に必要なのは、単なる二幅ポインタではなく、三幅ポインタなんだ。データへのポインタ、high用のvtableへのポインタ、そしてasref用のvtableへのポインタだ。それは可能だ。本質的に不可能なことではないけれど、トレイトを増やすにつれて、この参照のサイズがどんどん大きくなってしまうということだ。

[1:04:55] そしてそれはおそらく意図したものではないだろう。そこで、コンパイラが組み合わせ用のvtableを生成して、それを渡すことはできないのかと思うかもしれない。理論上はそれができる。Rustコンパイラは現在これをやっていない。それをするという提案は知らない。理由の一つは、pub trait high asrefと書いて、その型がhighかつasref strであることを要求し、独自のメソッドを持たないようにすることで回避できるからだ。

[1:05:28] そして今、これができる。そうだろう?なぜなら今はvtableが一つだけで、そのvtableはhigh asrefであり、コンパイラはこのトレイトのvtableを生成する必要があるとき、両方のトレイトのすべてのメソッドが含まれることを知っているからだ。だからこのvtableはhighメソッドとasrefメソッドの両方を持つので、より大きくなる。だからこれがRust自体に取り入れられていない理由の一部は、自分でオプトインできるからだと思う。プラスを自動的に大きなvtableに変えないことで、開発者にこれは意図したものではなかったかもしれないと伝え、もしそうなら代わりにこれができると示しているんだ。

[1:06:12] ここのコンパイラエラーはもっと良くできたはずだということには賛成だ。Esteban Cooperの誰かが言っていたように。たぶん、ここで自分でトレイトを生成できることを人々に知らせることができるだろう。誰かが書いたと思う、たぶんi plus s refだ。

[1:06:52] かき混ぜて、それが本当かどうか見てみましょう。ええ。わかりました。つまり、これが正しいコンパイラエラーを得る方法で、それは自動トレイトだけがトレイトオブジェクトの追加トレイトとして使えるというものです。一方ここでは、二つの異なるトレイトの例があり、どちらも自動トレイトではありません。それについてはすぐに話します。そしてここでは実際に、私たちが話した提案が示されていますよね?これらのすべてをスーパートレイトとして持つ新しいトレイトを作成し、代わりにここでそのトレイトを使うことを検討してください。また、sendやsyncのような自動トレイトは問題ないことも指摘しています。

[1:07:27] そして基本的な考え方は、マーカートレイトの場合、例えばhighプラスsendと言いたいとき、sendにはメソッドがありません。なので、Vテーブルが空でも問題ありません。したがって、そこにメソッドがないので、Vテーブルの追加部分を保存する必要はありません。だから、メソッドのない追加トレイトを持つことが許されるのです。自分で作ったものは使えないと思います。例えばFuchsトレイトを作って、これプラスFuchsと言っても、うまくいかないと思います。

[1:08:00] しかし、トレイトがメソッドを決して持たないことを宣言するマーカーアノテーションを持つという提案がいくつかありました。しかし、それは現在私たちが持っているものではありません。少なくとも当面は、これがやるべき方法です。素晴らしい。

[1:08:34] わかりました。これがトレイトの組み合わせでどのように機能するかです。しかし、トレイトオブジェクトが少し制限される例はこれだけではありません。もう一つは、highに対して、実際に、まず関連型を追加したとしましょう。それをnameと呼びます。そして実際には何にも使わず、ただ一つ追加するだけです。コードはすでにコンパイルできません。なぜコンパイルできないのでしょうか?

[1:09:05] ええと、関連型の値は...ああ、それは実装です。それをしましょう。つまり、これはtype name equals unitになります。型については実際には気にしないので、両方にそれを使うだけです。ええ、ここではトレイトhighの関連型nameの値を指定する必要があると書かれています。つまり、ここでdyn highを取るところで、実際に関連型を指定する必要があるのです。

[1:09:39] 関連型が何であれ、任意のhighを取るとだけ言うことはできません。そしてここでの理由は、その情報はVテーブルに捕捉できないからです。これは型だからです。バイナリ内にアドレスがありません。Vテーブルに入れられるものが何もありません。したがって、これはトレイトオブジェクトでは直接機能しません。代わりに、言わなければならないのは、nameがこれであるhighを取るということです。そしてここでも同じことをする必要があると思います。

[1:10:15] そしてそれでうまくいきます。なぜなら今、highを実装し、関連型がnameであるもの専用のVテーブルがあるからです。なので問題ありません。これはあまり面白い変更ではないので元に戻しましょう。もう一つの、おそらくより興味深いケースは、例えば…何と呼びましょうか?「weird」と呼ぶことにしましょう。何もしない奇妙な関数を用意します。

[1:10:48] 誰もそれを実装する必要はありません。そしてこれもコンパイルできないことがわかります。cargo checkでエラーになります。もう少し小さくして、少しでも理解しやすくしましょう。まだ読めるといいのですが。おお、とても冗長ですね。エラーを少し見やすくするために、組み合わせトレイトの部分をコメントアウトしましょう。さて、これはhighトレイトをオブジェクトにできないと言っています。

[1:11:24] つまり、dyn highと言うと、基本的にはhighトレイトがオブジェクト安全ではないと教えてくれています。すなわち、トレイトオブジェクトに変換できないのです。そして、トレイトがオブジェクト安全であるためには、呼び出しを動的に解決できるようにVテーブルを構築できる必要があると言っています。これがこれまで話してきたことです。特にここでは、関連関数weirdにselfパラメータがないため、トレイトをオブジェクトにできないと言っています。なぜそれが必要なのかについてはあまり説明していませんが、順を追って見ていきましょう。

[1:11:56] 繰り返しますが、ここのsayHiの中で、今s.weirdを呼び出そうとしているとしましょう。このコードを書いたらコンパイラはどうするでしょうか?実際にはこのコードは書けません。なぜならweirdはselfを取らないからです。何かへのポインタも取りません。そして勝手にそれへのポインタを構築することもできません。なぜならポインタを持つには有効なインスタンスが必要だからです。

[1:12:28] つまりこれは本当に、hi::weirdのようなものです。奇妙に思えるのは言うまでもありません。なぜならここでどの型に対してweirdを呼んでいるのでしょうか?ここには、どのweird実装を望んでいるかを指定するものが何もありません。この特定のケースではデフォルトを提供しているので、問題ないと思うかもしれません。しかし、Stringに対するweirdの実装があったらどうでしょうか?

[1:12:58] それがトレイト上のものと異なっていた場合、それは許されていますよね。デフォルト実装をオーバーライドできます。では、これはstr用のものか、トレイトのデフォルトか、それとも全く別のものを呼ぶべきかをどうやって知るのでしょうか?Sがここにないので、Vテーブルには入れられません。weirdメソッドは自身を取らず、どの型のどのインスタンスにも関連付けられていません。なのでこれはうまくいきません。意味のあることではないのです。

[1:13:32] しかし、本当にこれが欲しかったらどうでしょう?例えば、その奇妙な関数を存在させたいけれど、トレイトオブジェクト経由で呼び出すことには関心がないとします。関心があるのは high だけです。トレイトオブジェクト経由で。つまり、high をトレイトオブジェクト安全にしたいけれど、トレイトオブジェクトの high があっても、weird を呼べなくても構わないということです。そうすれば、こうできます。こうです。

[1:14:09] そしてここに戻って、もう一度 high に speed を持たせます。s ドット a。つまり、ここで言っているのは、weird 関数は、トレイトを実装する型である self が sized であることを要求するということです。そして、トレイトは sized ではないことを思い出しましょう。単に dyn high のようなものは sized ではありません。ポインタ型の背後にある場合にのみ sized になります。

[1:14:43] つまり、これは V テーブルからオプトアウトする方法だと考えることができます。この関数は V テーブルに配置すべきではなく、決定的にトレイトオブジェクト経由で呼び出せないようにすべきだと言っています。これが意味するのは、ここで、静的バージョンは邪魔なので削除しましょう。これが意味するのは、今やコードは問題なくコンパイルされるということです。hi を呼べますし、それのトレイトオブジェクトも作れます。しかし、ここで、実際さらに進めて、この関数に self があったとしてもオプトアウトしたいとしましょう。

[1:15:22] それでもこれはコンパイルされ、依然としてトレイトオブジェクトを作れます。しかし、ここで weird を呼び出そうとすると、コンパイラは、weird メソッドはサイズ要件があるためトレイトオブジェクト上で呼び出せないと教えてくれます。つまり、これは、トレイトがオブジェクト安全であり続けることを確実にするために、任意の関数をそれに含めることからオプトアウトする方法です。また、where self は sized と書くことで、トレイト全体をトレイトオブジェクトに変換できないようにすることもできます。

[1:16:01] これをすると、基本的にこのトレイトをトレイトオブジェクトとして使うことを禁止することになります。実際にはこれはまれです。通常、トレイトは中のメソッドのせいでオブジェクト安全でないだけです。トレイトオブジェクトを禁止することを選ぶのはまれです。後方互換性の理由でそうすることがあります。例えば、後でオブジェクト安全でないメソッドを追加するかもしれないと分かっている場合、先回りしてこれを追加することがありますが、かなりまれです。

[1:16:36] では、ここまでの制約は理解できましたか?関連型の問題は静的ディスパッチでも起こりますか?いいえ、起こりません。その理由は、静的ディスパッチでは単相化されるため、任意の関数実装について具体的な型が実際に分かるからです。s コロンコロン weird が可能かもしれません。

[1:17:10] これは、まだfn weirdがあった頃の話ですね?ここにオーバーライドもあったとしましょう。そして、例えばこんな特別な構文を追加して、sの型に対してweirdメソッドを呼ぶ、というふうにしたかったとします。weirdがトレイトオブジェクトのvtableに含まれるようになったとしても、self引数付きでは呼び出さないと分かっている、と想像できます。ここでの課題は、これがちょっと奇妙だということです。

[1:17:45] 呼び出すのにその型のインスタンスがどうしても必要なら、なぜ単にselfを取らないのでしょうか?これの伝統的な例は、weirdが実際にはnewとかnewに似た何かと呼ばれている場合ですよね?その場合、すでにその型のインスタンスを持っているなら、そもそもそのメソッドを呼ぶ必要はありません。単にselfを取るだけです。なので、こういうものも可能かもしれないというのは同意します。ただ実際には、たいていあまり有用ではないのだと思います。

[1:18:19] だからこそ、優先度が高くなかったのです。追加されないもっと深い理由があるのかもしれません。それは分かりません。ええと、where self: sized があると、具体的なDSTに対してトレイトを実装することも禁止されるのでしょうか?それは良い質問ですね。つまり質問は基本的に、where self is sized がある場合、Box>に対して実装できるのか、ということです。

[1:18:58] 例えばそうですね。できると思います。これが可能であるべきだと言う理由は、ええ、これはもうトレイトオブジェクトにはできないので動きませんが、それでもこの実装は持てるはずだからです。なぜこれが?ああ、そうか、Boxだからですね。なので二重のsrefが必要です。これは問題ありません。これは動的サイズ型ではないからです。

[1:19:35] 繰り返しますが、ポインタの後ろに包めば、サイズを持つようになります。動的サイズ型ではありません。なので、トレイトにself-sizedがあっても、それを妨げることはありません。関連型の制限は奇妙に感じます。関連型の要点は、任意の具体的な型に対して一つしか存在しないということだからです。ならばvtableは関連型が何であるべきか知っているはずでは?型へのポインタは持てませんが、トレイトの実装はコンパイル時にその型が何かを知っているはずです。

[1:20:07] ええ、問題は型が消去されることです。残るのはvtableだけです。なのでvtableからは、元の具体的な型が何だったかを知ることはできません。これには例外があり、それはanyトレイトです。anyトレイトには、元の具体的な型の型記述子を返すメソッドがあります。これを理解できなくても大丈夫です。無視してください。ともかく、これを何とかごまかす方法はいくつかあります。しかし基本的に、トレイトオブジェクトは型消去されています。

[1:20:38] 使っていた型に関する情報を保持することはできない、という感じです。ああ、strやu8のような型のことですね。いいえ、それはできません。where self is sizedがある場合、Selfはsizedでなければなりません。TraitObjectsで生じるもう一つの制約は、メソッドをジェネリックにできないことです。これについては、奇妙な高度なトレイトをいじり続けるのではなく、標準ライブラリに移ってfromIteratorトレイトを見てみましょう。

[1:21:16] つまり、fromIteratorトレイトは、例えばVecによって実装されているものです。collectがどのように動くかというと、VecがfromIteratorを実装しているからです。そして、ええと、iteratorのcollectを見てみるのが一番いい方法でしょう。イテレータのcollectは、collect先のものがfromIteratorを実装していることを要求します。だからイテレータからvecにcollectできるのは、vecがfromIteratorを実装しているからです。ただ、fromIteratorトレイトは少し変わっています。トレイトのA型は、イテレータの要素の型です。

[1:21:55] しかし、fromIterator型自体がTを取ることもわかります。ここでのTはイテレータの型ですよね?なぜなら、例えばvecでなければならないからです。イテレータが何であるかは気にしません。どんな型のイテレータからでもvecを構築できます。ただし、要素がTである任意のイテレータからvec Tを作成できます。これはおそらくiterのIと呼ぶべきですが、それほど重要ではありません。ここで、aは最終的にvecになるものの種類です。

[1:22:30] つまり、このaが例えばboolなら、boolのvecになるわけです。そしてtはイテレータの型で、例えばHashMapのイテレータとか、そういう型になるかもしれません。しかし、これはTraitオブジェクトにとって問題になります。これに対してコードを書こうとすると想像してみましょう。では、これをちょっと消します。実際、新しいものを書きます。このファイルの残りを全部消します。そして、ここで何をしましょうか、collectをやりましょう。

[1:23:09] 標準のiterからfromIteratorへ、boolのfromIteratorを取ります。そしてvecを返します。そしてs.collectをします。おっと、何をしたんでしょう?変なことをしましたね?すごい。これは問題ないはずですよね?何でも取ります、取ります。

[1:23:42] ええと、実はこれはいくつかの理由で変です。fromIteratorはここでは悪い例かもしれません。なぜなら、これもselfを取らないからです。だから実際にはselfがsizedであることを要求します。Extendの方が良い例です。ここでextendを掘り起こしましょう。すごい。では、代わりにextendを使います。そして、ミュータブルを取る必要があります。では、mut vはnewで戻り、そしてv.extendをします。

[1:24:18] 実は、そんなことはしません。これをVとして、v.extendを実行し、それに単一のboolを渡します。つまり、単一のboolで拡張します。trueを追加します。boolのイテレータで拡張可能なものを受け取り、単一のboolを生成するイテレータで拡張しようとします。

[1:24:49] つまり、trueを追加するだけで、取得したものにtrueを追加します。ここでも、extendはオブジェクト安全ではないため、トレイトextendをオブジェクトにできないと表示されます。extendを見ても、これまで見てきたことからすぐには理解できません。そうでしょう?繰り返しますが、これはイテレータの要素の型に対してジェネリックです。それは問題ありません。extendはselfを取ります。つまり、Vテーブルに入れられるものがあります。インスタンスがあれば、このメソッドの呼び出し方はある程度わかります。しかし、繰り返しますが、イテレータの型に対してジェネリックであることに注意してください。

[1:25:23] ここが本当に奇妙なところです。vecの内部を想像できますよね。impl T, extend T for vec Tが存在するでしょう。そして、この実装を持つでしょう。こちらの方が役立つと思うので、これをIと呼ぶことにします。そして、ここに何が入るかは誰にもわかりませんよね?

[1:25:58] はい、その警告を取り除くためだけです。ええと、こうします。もう少し役立つようにしましょう。私のvecです。この実装は標準ライブラリのどこかに存在するでしょう?ただしvec用です。しかし、このメソッドはジェネリックです。単相化の議論から、コンパイル時に単一のextendにはならないことがわかります。

[1:26:35] このメソッドの複数のコピーになるのです。そうでしょう?例えば、標準コレクションのHashMapIntoIteratorを取る、HashMapIntoIterを取るextendルールになるのです。そうでしょう?実際、それ以上に、impl全体がジェネリックなので、実際にはこうなります。

[1:27:13] それが実際に実装される、つまりコンパイラによって生成されるメソッドです。誰かがboolのHashMapイテレータを使って拡張しようとした場合を想定しています。単一のextendは存在しません。イテレータと要素の型の組み合わせごとに存在します。では、Vテーブルには何が入れられるのでしょうか?boolを拡張したいということは確定しています。

[1:27:44] なので、それは問題ないですよね?つまり、ここでTを考慮する必要はありません。なぜなら、すでにそのTを選んでいるからです。しかし、extend自体については、Vテーブルの中で、boolに対するこのイテレータ型のextendへのポインタを本当に持つ必要があります。しかし、それは関数の型では表現されていません。そして、それを表現する方法すらありません。そうです、extendの実装が標準のiter one spoolなのか、それとも何かすごく奇妙なものなのか、想像するしかないのです。

[1:28:26] しかし、書かれている方法では、ここにはVテーブルが標準のiter onceに対するextendの実装を指すようにしたいとは何も書かれていません。そこに問題があります。コンパイラがこのコードを生成しようとすると、extendの適切な実装へのポインタがありません。したがって、Vテーブルを生成できません。dinExtendのVテーブルを生成することはできません。なぜなら、extendの可能な実装ごとに一つのエントリがあり、無限の数のエントリを持つことになるからです。

[1:29:02] したがって、答えはdinExtendは存在できないということです。extendのトレイトオブジェクトを作成することはできません。よろしいですか、理解できましたか?これはやや複雑な説明ですが、うまくつながっていることを願っています。ええと、Rossiは、extendが呼び出される各Tに対して、extendを実装する各型にモノモルフィズされたバージョンのextendを追加できるでしょうか?それは魅力的ですが、常に可能とは限りませんよね?

[1:29:36] このコードをコンパイルしていると想像してください。しかし、ええと、標準ライブラリだけでも、標準ライブラリにはextendの使用がたくさんありますが、そのクレートに依存するクレートでは、さらに多くの型でextendを呼び出すかもしれません。したがって、Vテーブルのサイズは、一番下のクレート、つまり標準ライブラリをコンパイルするとき、本質的に、標準ライブラリのdin extendのVテーブルは、クレートのdin extendのVテーブルとは異なるということになります。

[1:30:12] さらに上のクレートでは、使用したいイテレータの実装がより多く存在する可能性があるためです。そして、今度はdinExtendに対して多くの異なるvtable実装、または多くの異なるvtableを持つことになります。それは組み合わせ爆発のような問題になるでしょう。また、標準ライブラリのdinExtendを、さらに上のクレートでdinExtendを受け取るものに渡すことができないことも意味します。なぜなら、それらのvtable型が異なるからです。よろしい。

[1:30:54] つまり、これができない理由です…トレイトがオブジェクト安全であるためには、ジェネリックメソッドを持ってはいけません。すべてのメソッドにselfを含むレシーバが必要です。さらに別の要件として、トレイトがselfを返す型を持つことはできません。ここで少し戻ってcloneを考えると、DynCloneでないものを受け取り、cloneを呼び出そうとします。なぜならDynCloneでできることはそれだけだからです。

[1:31:37] そうですよね?DynCloneがあれば、トレイトが許すことだけができ、cloneが許すのはcloneだけです。つまり、cloneトレイトはオブジェクトにできないということです。これはよく見るエラーです。これができない理由は、cloneトレイトにselfを受け取りselfを返すFN cloneがあるからです。では、let x = v.cloneとしましょう。xのサイズは何でしょう?DynCloneはクローン可能な任意の型にすぎません。

[1:32:16] そして、参照ではなくselfを返すはずです。参照DynCloneを返すのではなく、参照を受け取ってselfを返すのです。つまり、ここでのselfはDynCloneなので、DynCloneを返すべきということになります。なぜなら具体的な型を消去しているからです。しかしDynCloneはサイズ付きではありません。つまり、このメソッドの戻り値はサイズ付きでないことになります。そして、関数の戻り値の型は、コードを生成するためにサイズ付きでなければなりません。

[1:32:49] したがって、これは機能しません。トレイトがオブジェクト安全であるためには、selfを返すメソッドを持つことはできません。だからcloneができないのです。さて、highについて話したように、オブジェクト安全で単独でも有用なメソッドがいくつかある一方で、トレイトを非オブジェクト安全にする他のメソッドがたくさんあり、それらをトレイトオブジェクトを経由しない型のために含めたい場合があります。単に便利だからです。

[1:33:23] 実際、良い例はiteratorトレイトを見ることです。iteratorトレイトには、問題ない関連型itemがあり、nextがあり、nextはオブジェクト安全です。しかし、chainのようなジェネリックなメソッドや、selfを返すenumerate、mute selfを返すby refなど、たくさんのメソッドもあります。

[1:33:56] from iteratorに依存するcollectもあり、それはオブジェクト安全でないことはすでに知っています。では、なぜiteratorはオブジェクト安全なのでしょうか?実際にそうだからです。ここで言うと、itemがboolのDyn iteratorを受け取りたいとします。collectします。おっと、iteratorです。collectは呼べません。なぜなら、このメソッドはトレイトオブジェクトでは呼び出せないからです。

[1:34:30] しかし、次を呼び出すことはできます。これに対して次を呼び出すことは許可されています。ミュートしないと機能しません。それは問題なく機能します。そして、イテレータトレイトがこれを実現した方法は、よく見るとわかりますが、実際にイテレータトレイトのソースを見ると、これが表示されるはずです。ここで見つけるだけです。

[1:35:03] 例えば、selfを消費するcountはそうですね。つまり、参照の後ろに行くことは許可されておらず、それはsizedになり、where self is sizedを持ちます。同じであるlastまでスクロールすると、self is sizedです。chainを見ると、chainはジェネリックであるため、通常はトレイトをオブジェクト安全でなくしますが、where self is sizedを持ちます。その理由は、基本的に、これは奇妙な関数で行ったのと同じことです。where self is sized境界を使用して、このトレイトをトレイトオブジェクトとして使用する目的ではこの関数を無視すると言えます。

[1:35:41] 基本的に、Vテーブルに入れようとしないでください。つまり、誰かがトレイトオブジェクトを持っている場合、そのメソッドを呼び出すことはできません。しかし、トレイトオブジェクトを持っていない場合、例えばVecのイテレータや具体的な型を持っている場合、このメソッドを呼び出すことができます。したがって、これは、いくつかのメソッドがあると便利だが、トレイト全体をオブジェクト安全でなくすることなくオブジェクト安全でないトレイトを持つ方法です。ええと、レシーバはselfを含む任意のものにできますか、それともref selfまたはmut selfでなければなりませんか?

[1:36:16] ええと、このルールは実際には、ええと、どこにこれを持っていますか?どこかで開いています。ちょっと待ってください。ここです。これはオブジェクト安全性に関するRust言語リファレンスからのものです。そして実際、今までにこれらのほとんどをカバーしました。すべてのスーパートレイトもオブジェクト安全でなければなりませんね?なぜなら、すべてのスーパートレイトの和集合からVテーブルを構築するからです。Sizeはスーパートレイトではありません。

[1:36:47] つまり、self: sizedを要求する場合、オブジェクト安全ではありません。関連する定数を持ってはいけません。これもまた、定数を置く場所がないためです。理論的には、Vテーブルに置くこともできるかもしれませんが、Vテーブルが非常に大きくなります。また、Vテーブルの値はすべて関数ポインタではなくなります。任意のサイズのものになる可能性があります。すべての関連関数は、トレイトオブジェクトからディスパッチ可能であるか、明示的に非ディスパッチ可能でなければなりません。

[1:37:19] つまり、ディスパッチ可能な関数は型パラメータを持てないため、ジェネリックではありません。self型を使わないメソッドである必要がありますよね?レシーバの型を除いて、具体的な型です。つまり、例えばselfを返すようなものは持てません。レシーバは以下の型以外にはできませんよね?selfへの参照、selfへの可変参照、Box、Rc、Arc、またはPin、いやPin<&mut Self>ですね。つまり、ポインタの背後にあるもの、基本的にはサイズ不定のものをサイズ付きに変換できるものなら何でもです。

[1:37:55] そして、これが明示的にwhere Self: Sized境界を除外していることがわかります。これにより、一部のメソッドがオブジェクト安全でなくても、オブジェクト安全なトレイトを持つことができます。これがディスパッチ不可能な関数です。ええと、ライブラリの作者は、下流の誰かがトレイトオブジェクトとして使いたい場合に備えて、非オブジェクトメソッドに常にwhere Self: Sizedを追加することを検討すべきでしょうか?私は yes だと思います。ええと、それはあなたのトレイトがそもそも使えるかどうかにも少し依存します。

[1:38:28] つまり、あなたのトレイトがトレイトオブジェクトとして使えない場合、例えばCloneを考えてみてください。そうすれば、確かにcloneメソッドにwhere Self: Sizedを追加して、人々がトレイトオブジェクトのcloneを作成できるようにできますが、そのトレイトの主要な関数を呼ぶことすらできません。なので、おそらく価値はありません。しかし、一般的に、トレイトが有用である場合、たとえオブジェクト安全なメソッドしか呼べなくても、他のメソッドをオプトアウトしてトレイト全体をオブジェクト安全にすることは理にかなうかもしれません。

[1:39:14] IteratorのlastにはSized制約がありましたか?Iteratorのlastにはあると思います。ええと、lastにwhere Self: Sizedがある理由は、ここでは見えません。rustdocによって隠されているのですが、それはレシーバのためです。参照の背後には行きません。selfを消費します。つまり、selfを取り、selfはSizedでないIteratorであり、関数の引数はSizedでなければなりません。

[1:39:47] したがって、lastはトレイトオブジェクトを通じて呼び出すことはできません。まだお伝えしていないことがもう一つあります。まあ、お伝えしていないことはたくさんありますが、トレイトオブジェクトに関して少なくとも一つあります。それは、トレイトオブジェクトにはちょっとした秘密があるということです。では、pub traitがあるとしましょう。いや、こうしましょう。これは、Dropは実はオブジェクト安全です。

[1:40:19] 奇妙に思うかもしれません。オブジェクトに対してできることがドロップだけなら、それは本当に面白いのでしょうか?実はこれはいくつかの状況で役立ちます。例えば、Crossbeamがこれをやっているのを知っていますが、ガベージコレクションをしたいけれど、オブジェクトをすぐにドロップしたくない場合です。それらを連結リストのようなものに入れておき、定期的にガベージをすべて回収したいのです。潜在的に異なる多くのものを一つの型に格納したいので、TraitObjectsが必要になります。そして、単にmute in dropsを格納する、あるいは技術的にはboxed in dropsだと思いますが、同じ効果です。

[1:40:56] これでは実際には何もできません。しかしここでは、vがスコープを外れると、btableを通じてdropDropが呼ばれます。これは「ちょっと待って」と思わせるはずです。なぜなら、sayHiで考えてみましょう。dinAsRef.stirを取ります。いや、実際にはboxedで考えてみましょう。

[1:41:30] その方が良いです。sがスコープを外れるとどうなるでしょうか?少し考えてみてください。boxを取得するので、ヒープ上にメモリ割り当てがあります。ここでそれを使うかもしれませんし、s.asrefを呼ぶかもしれません。それは高コストかもしれません。しかし、この関数が戻るときにsをドロップします。しかしboxをドロップするときは、メモリを解放しなければなりません。しかしこれはトレイトオブジェクトなので、持っているメソッドはasrefだけです。

[1:42:06] これに対する答えは、すべてのVtableにdropが含まれているということです。これをここでの暗黙のdropのようなものと考えることもできますが、実際には、任意のTraitObjectのVtableには、具象型のdrop関数へのポインタが含まれています。なぜならそれが単に必要だからです。また技術的には、少しの追加情報も含まれています。具象型のサイズとアラインメントが含まれています。これらが含まれている理由は、メモリを解放しなければならないboxのようなものの場合、その情報をアロケータに渡して解放を行う必要があるからです。

[1:42:44] そして、すべてのトレイトオブジェクトには、V、つまりすべてのトレイトオブジェクトのVテーブルには、トレイトのメソッドに加えて、drop、サイズ、アラインメントが含まれています。通常はこれを考える必要はありませんが、この話題のついでに知っておく価値があります。少し話題を変えると、これまではトレイトオブジェクトについてしか話していませんでしたが、サイズが決まらない他の型もあります。例えば、dinトレイトはサイズが決まらないことを知っていますが、u8もサイズが決まらず、strもサイズが決まりません。

[1:43:20] これは、参照やポインタの後ろに置くと、データへのポインタとvtableへのポインタのタプルに変換されます。これは、サイズ付きにしたりポインタの向こうに置いたりすると、ワイドポインタにもなります。一方がデータへのポインタで、もう一方は単なるu-size、つまりスライスの長さです。strも同じで、データへのポインタと長さのu-sizeになります。

[1:43:57] だからこそ、u8を受け取る関数fooを書こうとすると、コンパイラは型U8の値のサイズが不明だと怒ります。U8は任意の長さのU8のリストを意味するだけで、サイズ付きではないからです。したがって、それを引数として関数を呼ぶことはできません。単にU8のシーケンスをそのまま返そうとしても同じですよね?U8を返すbarがあった場合も。

[1:44:33] ええと、それも文句を言います。おっと、そもそもそんなことさせてくれるんでしょうか?ほら、できました。型を構築しました。ここでも同じことが言われています。型U8の値のサイズは不明で、関数の戻り値の型は静的に既知のサイズでなければならない、と。つまり同じ問題です。ここでも、サイズなしのものからサイズ付きのものへ移行する方法は、サイズなし性を覆い隠せる型の後ろに置くことです。参照を使うか、boxを使うかですね。

[1:45:14] これのboxもできます。これは許されると思います。よし。これでサイズ付きになったので問題ありません。そのサイズはワイドポインタで、一方がデータ、もう一方が長さです。そしてコンパイラは、この型にアクセスするときにポインタを分解して長さを得ることを知っています。

[1:45:51] boxや生ポインタでも同じです。文字列も同様です。これらは少し魔法めいています。これを標準化しようとする作業もありました。現在、動的サイズ型はコンパイラ内で少し特別扱いされています。ポインタがワイドかどうかを知る必要があるからです。そのため、サイズなし型を自分で扱うのはかなり難しいです。たとえばboxを自分で実装してサイズなし型を受け取ろうとする場合、可能ではあります。

[1:46:27] キャストやトレイトオブジェクトの許可などに踏み込むとかなり面倒になります。しかし最近、RFCが承認されました。RFC番号2580で、ファットポインタのメタデータを操作するための汎用APIの追加について述べています。これにより、ファットポインタの二番目の部分の型を指定するようなことができます。そうです。実際、ここを少し下にスクロールして、DINトレイトがメタデータがDINメタデータであるpointyになるのを見てみましょう。

[1:47:09] そして、私たちはDINメタデータです。は、型のサイズ、型のアラインメント、dropとplaceへのポインタ、そしてトレイトの簡略化のための型のすべてのメソッドへのポインタなど、すべての情報を表すVtableへのポインタです。つまり、ちょうど今話したとおりです。同様に、このpointyトレイトは、参照なしのU8スライスのようなものに対して実装され、メタデータはそのものの長さであるUサイズになるだろうと想像できます。

[1:47:44] これはまだ非常に新しく実験的なものです。このRFCを読むことを強くお勧めします。これについてもっと学びたいなら、本当に魅力的です。これには、メタデータが空であるpointyを実装する任意の型であるtrait alias thinのようなものがあり、それはポインタに付随するメタデータを持たないもの、つまりファットポインタではなくシンポインタであるものすべてです。そして、本質的にポインタのメタデータを内省するためのメソッドがあり、実際にVtableを見るようなことができるようになります。

[1:48:16] これについて先ほどチャットでいくつか質問がありました。このRFCは実際にその情報を内省し、決定的にVtableをオンザフライで構築できるようにします。つまり、コンパイル時に知られていないが、実行時に構築するものを持つことができます。そして実際、私が知る限り、これはすでに標準ライブラリの一箇所、asyncの領域のwakerのために存在しています。wakerトレイトについてはあまり詳しくは立ち入りませんが、ここでお見せするwakerトレイトです。

[1:48:48] ええと、私が嘘をついているwakerです。つまり、wakeトレイト、ああ、wake、waitではなく、raw wakerです。ああ、それに対するトレイトはありません。だから、ええと、実際にcontextをお見せしましょう。contextはwakerを提供します。Wakerはwake、wake by ref、willWake、fromRawというメソッドを持つ構造体で、dropとcloneができます。

[1:49:24] しかし実際には、wakerは本当にジェネリックです。見た目にはジェネリックではないだけです。しかしwakerの内部にはraw wakerがあります。そしてraw wakerは、内部を見ると、データポインタとvtableポインタです。つまり、本当にデータポインタです。動的ディスパッチですが、ある意味隠された形で、vtableはraw waker vtableであり、raw waker vtableは、cloneメソッド、wakeメソッド、wake by ref、そしてdropのための関数ポインタを与えることで構築します。

[1:50:03] つまりこれは基本的に手動で構築されたVtableで、トレイトではなく型を通じて動的ディスパッチを提供するものです。これについてはあまり詳しくは立ち入りませんが、標準ライブラリにおける手動で構築されたVtableの例として示したかっただけです。ここから他に話したいことはあるでしょうか?ないと思います。では、しばらく話し込んでしまったので質問に移りましょう。

[1:50:38] U8への参照は開始ポインタと終了ポインタを持っていて、長さではないと思っていました。長さを持っていると思います。いや、その二つは基本的に等価です。あなたが正しいかもしれません、忘れました。実際、この参照が何と言っているか気になりますね。ええ、ご覧のとおり、このRFCはNightlyに存在するトレイトオブジェクト関連のものも非推奨にしています。これが置き換えだからです。

[1:51:11] Pointyトレイト、薄いメタデータ、生パーツから。定義はどこに…ああ、実際には示されていませんね。ええ、ここにスライスの実際の関連メタデータ型が書かれていることを期待したのですが、見当たりません。

[1:51:42] 単に長さだと思います。独自の動的サイズ型を作れますか?ある意味では。では、こう書けます。ここでfooはもうサイズ不定です。実際、さらにフィールドを追加できます。ただし、この後にフィールドを追加することはできません。これがサイズ不定になった後では、ですよね?

[1:52:14] なので、これをやろうとすると、u8の値のサイズはコンパイル時に知ることができないと告げられます。動的サイズ型を持てるのは構造体の最後のフィールドだけです。フィールドの型を静的に既知のサイズを持つように変更してください。借用型は常に静的に既知のサイズを持ちます。つまりこれが言わんとしているのは、最後のフィールドであれば、先ほど私がした議論を思い出してください。もしここ中間にサイズ不定型があり、foo.xを参照したいとして、fooへのポインタしか持っていない場合、中間の型が任意のサイズを持ちうるときに、どうやってxへのポインタを得るのでしょうか?

[1:52:54] 答えは、できない、です。tが任意のサイズなので、xのアドレスを得る方法が分かりません。しかし、最後にあれば問題ありません。fのオフセット、xのオフセット、tのオフセットを静的に知ることができます。そしてこれをサイズ付きにするために必要な唯一の情報は、最後のフィールドの長さです。したがって、このような型を構築することが許されます。この型は今やサイズ不定です。しかし、at fooを持てば、その型はfooへのポインタとtの長さを併せて格納することでサイズ付きになります。

[1:53:34] こうして独自の動的サイズ型を作れます。box U8はvec U8と同じものですか?これは、参照の背後ではなく、U8スライスのboxを持っている場合、vec U8です。同じではありません。いいえ。では、こうしましょう。

[1:54:05] それらは同じではありません。同じように感じられますが、同じではありません。おっと。Vecは成長できます。まず、Vecは三つの単語から成ります。ヒープ上のベクタへのポインタ、ベクタの長さ、そしてベクタの容量です。これにより、容量内でプッシュしようとすると長さが増えるだけです。容量を超えてプッシュしようとすると、ベクタ全体が再割り当てされ、コピーされ、変更されます。

[1:54:39] ボックスU8では、それはできません。これは決して伸びたり縮んだりしません。プッシュすることもできません。これはただの、スライスだと考えてください。本当にただのスライスです。VecuateをBoxuateに変換できます。また逆方向にもできます。しかし、それらは同じではありません、いいえ。dinfnとfnの違いは何ですか?

[1:55:28] つまり、dinfnを受け取るfn fooを書けます。そして、fnを受け取るfn barも書けます。これらの違いは何ですか?これらは同じではありません。これは関数でなければなりません。クロージャにはできません。その理由は、fnは実際には関数ポインタだからです。

[1:55:59] 単なるアドレスでなければならない単一のポインタのようなものです。これはvtableです。トレイトオブジェクトであり、ここで考えられるvtableには関数を呼び出すためのポインタがありますが、データポインタも持っています。なぜなら、この構造はワイドポインタであり、一方の部分がvtableで、実際に関数を呼び出すためのポインタを持ち、もう一方の部分がデータポインタです。そして重要な違いは、fn mainがある場合、クロージャでfooを呼び出せることです。

[1:56:41] つまり、関数でできます。これですが、barでは同じことができません。なぜ文句を言っているのですか?ああ。そう、fooをクロージャで呼び出せるのは、これがxをキャプチャするからですよね?

[1:57:16] つまり、単なる関数ポインタではなく、関数ポインタとクロージャが環境からキャプチャするデータです。つまり、クロージャを呼び出すとき、クロージャの本体で必要とされるxのアドレスも提供する必要があります。そして、それがワイドポインタのデータ部分で渡されます。barの場合、実際の単なる関数ポインタが必要であり、データを置く場所がないため、クロージャを渡すことはできません。dinfnをimplfnの代わりに使う場合、そう、baz f implfnもあります。

[1:58:03] ええと、Bazをクロージャで呼び出せます。何ですか?何について文句を言っているのですか?Bazをクロージャで呼び出せるのは、implfnはfnであるものに対するジェネリック関数の糖衣構文だからです。

[1:58:34] つまり、渡されるクロージャの型ごとに baz の具体的なコピーが実際に生成されます。したがって、各クロージャごとに単相化されるため、データも簡単に渡すことができます。そこで問題は、いつ dinfn を使い、いつ implfn を使うのかということになります。基本的な答えは… implfn の方がより汎用的に使えます。例えば、ポインタを介した間接参照をする必要がありません。しかし、渡すクロージャの型ごとに Baz のコピーを生成することになり、それがかなり多くなる可能性があります。

[1:59:12] もう一つの理由は、ジェネリックにする代わりにトレイトオブジェクトを受け取りたい場合があるからです。そうしないと、ジェネリック型を上位に伝播させる必要があります。例えば、struct のラッパーがあって、その内部に関数ポインタを保持したいとします。これを保持させることができますよね。こう書けます。でもこれは、私のライブラリの利用者でラッパーを保持したい人は誰でも、自分自身も f に対してジェネリックにするか、f の型を名指しする必要があるということです。

[1:59:51] 一方、これが代わりに box din fn を格納するなら、ラッパーはもはやジェネリックではないので、呼び出し側はそのジェネリックパラメータについて考えたり伝播させたりする必要がありません。ですから、インターフェースが整理されて使いやすくなる場合があります。トレイトをオブジェクト安全にするという例もあります。fn foo を持つトレイト x があるとして、これを impl fn を受け取るようにすると、x はオブジェクト安全ではなくなります。

[2:00:28] クロックスを書くことはできませんでした。これは self を受け取るようにしましょう。トレイト x は、これがジェネリックなのでオブジェクト安全ではありません。implfn は、f が fn であり、これが f であると言うのと同じです。

[2:01:01] そして、先ほど話したように、これはオブジェクト安全にすることはできません。しかし一方で、これを dinfn にすると、オブジェクト安全にできます。なぜなら foo は一つしかないからです。つまり、V テーブルに無限のエントリが必要になるという問題はなく、foo は一つだけで、それ自体がワイドポインタを受け取るので、オブジェクト安全になり得る任意の型に対して機能します。ですから、ここに明確な答えはありません。ええと、いいですね。

[2:01:49] はい、これで話したかったことのすべてを網羅できたと思います。ただ一つ話せなかったのはコヒーレンスについてです。コヒーレンスは十分に異なる話題なので、この配信では話さず、別の配信で扱うかもしれません。特に二時間の節目でもありますし。ですから、ここで止めるのが良いタイミングだと思います。

[2:02:22] そしてこれを別々に行うだけです。ここまで話してきたことすべてについて、最後に何か質問はありますか?静的ディスパッチと動的ディスパッチの一般的な違い、サイズトレイト、Vテーブル、オブジェクト安全性、ワイドポインタとファットポインタ、これらすべては今おおよそ理解できましたか?それとも、なぜこれらがあるのか、何のためにあるのか、制限は何かを明確にし、あなたの頭の中で結晶化させるのにもっと説明できることはありますか?最後に質問を喜んで受け付けます。

[2:03:00] ランタイムのトレイト検出は将来、ある種のvtableを使って実装できるのでしょうか?質問を正しく理解したなら、できないと思います。つまり、トレイトオブジェクトやワイドポインタを取って、そのVテーブルを見るだけでどのトレイトを実装しているか分かるかということです。それはできないと思います。理由の一つは、トレイトオブジェクトごとに異なるvtableが生成されるからです。

[2:03:37] つまり、strやstringに対して一つのvtableがあるわけではないのですよね?stringには多くのvtableがあります。stringにはdynトレイトごとに一つのvtableがありますよね?ですから、どのトレイトを実装しているか分かるために見られる単一のVテーブルがあるわけではありません。例えば、dynトレイトであるSを取るfindトレイトのようなものがあれば、Vテーブルにあるのはここで指定したトレイトのメソッドだけです。

[2:04:24] 提供された型のすべての可能なメソッドのVテーブルを得るわけではありません。ですから、いいえ、この方法で何かがどのトレイトを実装しているかを動的に検出することはできないと思います。dyn fnを呼び出すと、Vtableポインタのために一度、その中の実際の関数ポインタのために一度、二重の間接参照が発生しますか、それとも最適化で消えますか?つまり、FnのFを取る呼び出しを行い、ここでFを実行するとします。

[2:05:07] それは良い質問ですね。二重の間接参照になると思います。なぜなら、まず通り抜ける必要があるからです... これは厳密には二重の間接参照ではありません。これはワイドポインタですよね?ポインタとVテーブルのタプルへのポインタではありません。実際に渡されるのは、あるTへのポインタです。

[2:05:39] ただTが何か分からず、TのFN Vテーブルへのポインタです。それが実際にここで渡されるものです。そしてこれはVtable.call of tのような呼び出しになります。ですからここに間接参照があります。これはVtableへのポインタです。

[2:06:12] ですので、Vtableを間接参照する必要があります。これが型を整理するより良い方法だと思います。呼び出しに到達するにはVtableを間接参照する必要があります。これはまさにこれですよね?呼び出しのアドレスを見つけるためにVテーブルを間接参照し、それを呼び出します。つまり間接参照が二回発生しますが、ポインタチェイシングとも少し違います。確かにその通りです。

[2:06:58] さて、少し変わった点が一つあります。例えば、din S ref strを取るSを持つXがあるとして、新しいポインタVtable動的メタデータRFCを使えば、s.Vtableがstring as din asrefster.Vtableと等しい場合、sを参照f sのデータをstringへの参照として、これがミュートのドットプッシュだったら、こういう本当に奇妙で醜い魔法ができるかもしれません。

[2:08:02] やらないことをお勧めします。でも、こうやってVテーブルを比較することは想像できます。コンパイラが型が常に正確に一つのVテーブルだけを持つことを保証するかどうかは分かりません。コンパイラはここでかなりの最適化も行います。box din FNをすると、エスケープ解析などで常にヒープ割り当てをするわけではないかもしれません。しかし一般的に、ジェネリクスを使う場合、実際のジェネリック型パラメータやimplブロック、失礼、implトレイトを使う場合、コンパイラがコンパイル時に全ての関連型を完全に把握し、実際の具体的な実装に基づいて共同最適化できるため、より良い最適化が得られます。

[2:08:52] 一方、動的ディスパッチによる間接参照があると、コンパイラは本来持っていた情報の一部を失い、それに基づく最適化ができなくなります。DINのsliceVecの簡単な例を見せてもらえますか?ああ、はい。say hiとしましょう。実際にDIN hiをやりたかったのですが、DIN asref stirにしましょう。そしてHとSに対して。

[2:09:27] Vにしましょう。SとV、S.asrefです。これを実際に動かすには、サイズ付きにするためにこうする必要があります。配列の全要素が同じサイズになるようにです。なぜなら、与えられたインデックスを見つけるためにそれが要求されるからです。そしてそうすれば、ソルトはただ動きます。

[2:09:59] また、内部の型にもボックスやアークなどを置くことができます。コンパイル単位が異なると、異なるVテーブルが生成されることがあります。それはだいたい合っています。少し逸話的な話ですが、Rustのコードをコンパイルするとき、Rustはコンパイルを高速化するために、一つのクレートを複数の独立したスレッドで異なるサブセットに分けてコンパイルすることがあります。しかし、それらの別々の単位をあまり同期せずに完全に並行して動作させたいので、両方が例えば…

[2:10:37] 文字列がdin-asrefとして使われている場合、Vテーブルの生成について調整したくないため、両方がそれぞれ独自のVテーブルを生成することがあり、その結果、同じ型・同じトレイトに対しても複数のVテーブルが存在することになります。これが、その不変条件が成り立たない可能性がある一つの例です。良い指摘ですね。そして、まだ話していないanyもあります。実際にデモはしませんが、anyトレイトがあります。anyはとても魔法のようです。

[2:11:09] 実際にはanyは単に、型の識別子を返す関数を持つトレイトにすぎません。その識別子はコンパイラによって一意であることが保証されています。したがって、anyに対するトレイトオブジェクトがある場合、その値の一意な型識別子を取得するためにVテーブルに追加されるので、それに対してtype IDを使うことができ、その型識別子が何であるか分かっているので、din anyから具体的な型へダウンキャストできます。anyについてはあまり深くは立ち入りませんが、anyはこれまで話してきたことの多くを使って、トレイトがanyを含む限り、din a dimトレイトから実際の基底型への参照へと変換できるようにしています。

[2:12:02] とてもクールで、今あなたが知っていることを踏まえると驚くほどシンプルです。ぜひ標準のAnyModuleのドキュメントを読んでみることをお勧めします。なぜこれが安全なのかについて書かれています。さて、ここで終わりにしようと思います。2時間と15、なかなか満足しています。たくさんのことをカバーしました。役に立ったなら嬉しいです。何か学べたと感じてもらえ、その一部が実際に身につくといいですね。私のコーディングライブストリームも少し進展があり、ぜひ実現させたいと思っています。

[2:12:36] できるだけ早く実現することを願っていますが、忘れてはいません。まだ取り組んでいます。皆さんお越しいただきありがとうございました。また次回お会いしましょう。それではさようなら!

英語の原文字幕を見る

[0:07] Hello folks, welcome back to yet another Crust of Rust. This one, I'm hoping I didn't bite off too much to cover in like an hour and a half to two hours. I guess by the time you watch this recording afterwards, you'll see whether I succeeded or not. So for this one, what I wanted to cover was... a sort of chunk of semi-related topics around traits and dynamic and static dispatch, the size trait, like wide or fat pointers.

[0:44] And some of the things around like V tables, coherence, they all have this kind of dynamic and static approach to them. They're all sort of tied together, some more so than others. And I get a lot of questions about each one. And I figured I should just do one stream where we talk through how all of this stuff works and how it fits together. I'm hoping that we don't... end up too far down any one rat hole. I think what I'll try to do is cover most of it in sort of workable detail.

[1:18] And then we might do sort of a deep dive on one of them in some later stream. But in order to try to contain it to the time, you might find that I skip over some of the detail, and hopefully that'll be OK. So I actually wanted to start this time on The Rust Book. So The Rust Book has a chapter on generic types and traits and lifetimes. And there's this one subsection in there on the performance of code using generics. And this is a section that, if you've read the book, and I highly recommend you do if you haven't already, might have struck you as, you might have read it and be like, that sounds like magic.

[1:59] And in some sense, what this stream is about is trying to deconstruct that magic and figure out what's inside. And in particular, it talks about this idea of monomorphization. And monomorphization is the, as the text says, the process of turning generic code into specific code by filling in the concrete types that are used when compiled. But that's sort of abstract. So let's try to pick up a slightly more concrete example and then work from there. Let's go with new lib.

[2:34] We're going to call this one. Hmm, naming is hard. It doesn't matter, but that makes it even harder because there are no constraints. We're gonna go with example written in Norwegian. All right, let's get rid of this test.

[3:06] We don't need no test. So let's say that you have a function greater. It is generic over T. Actually, let's go even simpler. Let's say that we're going to have a function strlen. And it's going to take anything that implements ASRF str. And it's going to give you back a use size. So we're going to do as ref len.

[3:39] Real simple function here. Let me make it a little bit larger. So this is a generic function. You could just as well have written it as s is s to use size where s implements s ref stir. These two are equivalent. s ref len. And I guess we'll make these pub to make the compiler stop complaining.

[4:12] So these two are equivalent. They're not quite equivalent, but they do the same thing. And both of them are generic functions. They can take in any type that can be turned into a reference to a star, which is what this says and same as what this trait bound does. And what happens is if we write any function, let's say foo, and it calls strlen of, let's say, hello world. And then it also calls strlen of string from hello world.

[4:53] in Norwegian. That is a good, handy shortcut for picking examples. So just to see why these are different, this is giving in a type of a static str. This is giving in the type of string. Whoa. Right? So this is where we get into the point of this function is generic. It doesn't just accept a string reference.

[5:25] It accepts any type that can be turned into a string reference. So string, for example, implements as ref str. Because if you have a reference to a string, you can trivially get a reference to a str. Because the internal representation of a string is a str. Right? So here we immediately see sort of why generics are useful. It's because it enables you to call into a given function in a more flexible or ergonomic manner. And behind the scenes, what happens, and this is what the Rust book is talking about when it talks about monomorphization, is that the compiler actually generates two copies of this function.

[6:08] one for each of these types. So at compile time, what we're actually going to end up with is like a sterling ref stir, which actually takes a stir and calls a stud Len. And we're going to end up and we're going to end up with a sterling string, which takes a string and does the same thing. So this one generic definition gets turned by the compiler into these multiple non-generic implementations.

[6:48] That's the process of monomorphization. And this is sort of key to how generics work in Rust. And this process doesn't just happen for functions, they happen for types too. So imagine that you have a hash map that's generic over the key and the value. You actually get a full copy of the entire struct and all of its methods, one for each type that it is used by. Notice that it doesn't generate... copies of this for types that we didn't invoke it with.

[7:18] This is not like a generate for every possible type. It is generate for any type sort of on demand, but on demand determined at compile time. If you see code that needs this function for a given type, then generate it at that point in time. And a type would be the same. Like a hash map would only, a particular instance of the hash map type would only be generated if that type combination actually appeared somewhere in the code. This is actually also one of the reasons why it's a little bit hard to make Rust, to compile Rust code and then ship people a binary that they can use as a library.

[7:58] Because imagine that if you had this in your Rust library that you wanted to sort of distribute in binary form, think like dynamically linked libraries and stuff, it's actually fairly complicated because The contract is that Rust is supposed to generate distinct copies of this function for each type, but it might be instantiated with a type in a consumer that isn't defined where the source function is defined in the originating library. And therefore, you need the source in order to generate all those instances.

[8:31] And the reason why monomorphization is great is because you end up producing potentially much more efficient code, right? Sterling is a bit of a bad example here, but let's imagine that we had something a little more complex. Actually, a good example is HashMap. I'm not going to write out the full definition of a HashMap here. But what you end up with HashMap is because you get a copy of the type for each concrete type you use. Imagine that one instance of the HashMap has the key be a...

[9:06] a string and another instance has the key be a number, you would actually end up with the compiler, when it generates the code for each of the methods of the HashMap, it would generate, like it would sort of inline the definition of say the hashing function for each key type. So the one, the HashMap version of the code that uses string would sort of put in the code for hashing a string directly into the HashMap code, and it could optimize that code based on the fact that that type is a string.

[9:40] Similarly, for something like a number, it might be able to skip hashing altogether because it realizes, once it sort of monomorphizes all the generics, that actually the hash is just the value of the number. That might not actually be true, but you get the sense of, like, the compiler gets to see the concrete written-out code for the particular types that are used. which lets it optimize a lot better. Does this all make sense before we move on to the more complicated aspects of this? Does the general idea of generics and why monomotivation is nice make sense?

[10:28] So the downside, as someone observed in chat, is, yeah, for monomorphization, one of the downsides is that your binary ends up being larger because you need to generate a copy of the type or the function for every type that it's used with. It's not quite as bad as like just multiply by the number of types. One of the reasons is because for HashMap, for example, you might only use a subset of the methods for any given type combination. And it won't generate like... Like if you ever have a HashMap that has string as the key type, it generates the entire HashMap, like all of the methods for HashMap for the string key type.

[11:08] It will only generate the methods you actually end up calling. So that amortizes the cost a little bit. But it is true that it leads to more code in the final binary. And a sort of side effect of that is that your code can be a little less efficient in the sense that now, rather than having one function called Sterlin, that like one sequence of like assembly, like machine code, really, that the computer can jump to.

[11:40] And then it can keep those lines of machine code like in cache, which lets it execute it more, more efficiently the next time around, what you end up with instead is you have two. different functions, and some code jumps to one and some code jumps to the other, and they have to be cached separately because they're separate regions of memory, as you actually end up with a slightly worse cache efficiency for your instruction cache, which is a downside. It's also a little bit expensive in the sense that the compiler does need to generate these copies, but usually that's not too much of a cost, like actually generating these, unless you end up instantiating with a very large number of types.

[12:22] Um, Is that one of the primary reasons Rust binaries are larger than C ones? So that is slightly different. Rust binaries statically compile more stuff, which might be part of the reason. Part of it is monomorphization. Part of it is, I forget the exact details, but I think there's more stuff from the standard library that gets compiled in. And another really big one is that Rust often builds in debug symbols.

[12:54] which if you don't strip them from the binary, you end up with a binary that has very little actual machine code, but a lot of debug symbols, as you might want to try to just strip the binary. Will the compiler try to inline generated functions? Yeah, so this is one of the reasons why monomorphization is really good, is because it doesn't just inline whether it's string or str, but if you have, say, a PubFn, like... a bool then, which takes a Boolean, and it takes an f, which is a function, and it returns you an option t.

[13:42] And then let's say the implementation is something like, if b, then some f else. And this function actually just landed in the standard library, although as a method on bool. So here, if you ever ran this function with a particularly provided... closure or function, it would actually generate a copy of bool then with the code for the closure you passed in directly inline into this function. And so it could be optimized accordingly.

[14:14] So yeah, it does end up inlining. Inlining is the wrong word here. It has the option of inlining and optimizing as based on that. It doesn't have to. It's just that because it gets monomorphized to the particular type, it knows exactly what that type is, and it can choose to inline if it wishes, which is an important distinction. Big reason for larger size is standard lib.

[14:44] That's not quite true because only the parts of the standard library that you actually use end up getting put into your binary. It is true, though, that if you're using a lot of generics from the standard library, that ends up growing the size. How big of a cost is duplication of methods? Basically none. I think the actual generation of multiple functions isn't that important, but what is important is if you generate many copies of a function, you have to compile each of them into machine code, which slows down the compilation process. Wouldn't strlen string take ref string rather than just string by value?

[15:23] It could take either, actually. They will both work, which is one of the reasons why taking askRefStir is nice. How do dynamic libraries handle generics? They don't. This is one of the reasons why it's challenging to do dynamic linking of Rust libraries, or even just distributing Rust libraries in binary form. And it's something that I think in Swift, they've been trying to stabilize something like this.

[15:54] We don't quite know how to use it for Rust yet. And yeah, you can't use it for something like if you want a C dilib, like a dynamically linked library in Rust that has a bunch of like external functions, those can't be generic. All right. So now that we have an idea of what monomorphization is, I want to talk a little bit about what the actual process of dispatch here.

[16:27] So dispatch is the idea of... Actually, let me give you a slightly better example that we can work with for a little bit longer throughout the stream. So let's define our own trait. We're going to call this trait... just call it Hello, it's simple enough, or I guess let's go with the Norwegian hi. And it just has one method.

[17:00] And let's say it actually returns nothing, it just has a symbol as a single function that just lets you say hello in Norwegian. And we can imagine that we implement that trait for let's say, stir. Um, and all that's going to do is it's going to print line, uh, self oops. Um, and then we're going to do, uh, I guess let's just go with J dot.

[17:40] Hi. Ah, can't type today. So what happens behind the scenes here is that when the compiler tries to generate the code for this, it determines the type of this, then it looks at which methods are available on just the str reference type. It doesn't find one called high. And then it looks at the traits that are in scope, it finds that there is a high method on this, which is implemented for the receiver type.

[18:18] And so it ends up calling that. Seems fine. Now let's imagine that we have a sort of generic version of this, where we take something that implements high, and I guess h. And it's just going to call h.high. So this one's trickier, right? When the compiler has to generate the machine code for this, it needs to somehow call this method, but it doesn't actually know the type of H. And this is where monomorphization comes into play, right?

[18:51] That in reality, what's gonna end up being generated is a bar str, which has H, B, str. And now, dispatching this, figuring out what to call here is trivial, because we know the concrete type. So this is what's known as static dispatch. That is, at compile time, the compiler knows what the actual type is. And therefore, when it tries to call this method, it just knows that that is this method.

[19:22] And it can just jump to, like this basically becomes a call in like assembly code to call this function, which is at some known location in memory, right? Because it's just where this method is. Does that make sense for static dispatch? That actually figuring out how to compile this code becomes trivial once you can generate this method, because this method is really the same as this. And these are both trivial to figure out where the high method lives.

[20:05] So now that we've looked at this sort of static dispatch, you might wonder, well, what is the alternative? What if we don't want to generate a bunch of different copies for this? So this is where we go back to dynamically sized types. Oh, sorry, yeah, impel-hi here is just syntactic sugar for generics. This is equivalent, like I showed with Sterling before, this is is equivalent to H is high.

[20:40] These two are equivalent. Yeah, so what then is the alternative? We don't want this monomorphization, we don't want multiple copies. Or the other reason why you might imagine this is, let's say that you want to let's say you have a vector of things that implement high. In foo here, I want to have a vector of this.

[21:21] And I want to do like for h in this vector, call h.high. That's fine if they're all the same type. But what if I wanted a sort of collection or sequence or set in some way of things that are high, but I don't need them to actually be the same type. All I care about is that they implement this trait. So more concretely, imagine that I want to write bar, and I want to take anything that is a, say, slice, of like, imple high.

[22:02] Let's start start with this version, right. So for H in s, h dot high. This works fine. I can call bar with say a with something like this. works just fine, that compiles just fine. Similarly, I can do I can turn each of them into strings. That also works just fine.

[22:40] Oh, right, I didn't implement this for string. So that works just fine. But let's imagine that I want to be able to call it with like, this should really be fine. But I can't do that, right? Like, I can't create a vector of things that are different types. That's not a thing that I can make in the first place. What I really, but in this case, I don't actually care what the concrete type is.

[23:11] I don't care that these are strings. All I care about is the fact that I want them to implement the height trait. That's all that matters to me. So I should be able to create a vector of things that have this behavior without caring about the concrete type. And this is where we get into the area of dynamic dispatch and trait objects. And the book has a chapter on this too. Let me find where that one is. I've opened it in the wrong order, which was silly of me.

[23:50] Sorry about the jumping around. It is down here in the chapter here. So the book has a pretty decent chapter where it talks about the ability to treat things that are different concrete types as the same type. So another example that they use is in the case of like a GUI, you might have lots of things that are drawable, like they implement the draw trait. And you might be able to take, you might want to have like a draw function that just takes a sort of list or iterator.

[24:25] of all of the things to draw. And some of those might be buttons, some of those might be images, some of them might be text boxes, but it doesn't really matter for the draw function. All it cares about is that it gets an iterator of things that are drawable, which has a similar sort of flavor to this, right, where we want to just take a slice of things that I can call high on. And what you need is what's known as a trait object. A trait object is where you see the din keyword.

[24:58] This isn't actually gonna compile. So what I'm gonna do is sort of, this is sort of what I want, right? So, imple, remember, is a shortcut for, and this is where it'll be useful to actually write out the types, is a shortcut for this. And this sort of gives a clue to what's going on. Bar is generic over one type, which has to be either a str reference or a string. It can't be both because it's only generic over one type. And you can imagine that we have like an H2 high here, but given that we're taking a slice or let's say an iterator there is nowhere to put h2.

[25:38] There is only the one iterator, which only has items of one type. So this won't really work. In some sense, what we want to say is that each of the things is a high. It doesn't have any other concrete type that we care about. And in fact, if we write this, we get a compiler error saying, let me pull this up on a new screen. It says, trait objects without an explicit din are deprecated.

[26:10] Okay, let's get rid of the warning first. It's saying we need to put din here, so we're just going to do that. And now it says, the size for values of type din high cannot be noted compilation time. So it points to this and says, doesn't have a size noted compilation type. The trait sized is not implemented for din high. Slice and array elements must have a size type. This is an error that you might have come across before. And part of what we're going to be talking about for some of the remainder of the stream is why we get this error, what it means, what the fix is, what sized means, and sort of how this ties into dynamic dispatch and trait objects.

[26:50] Let me pause here for a second because I've just thrown a bunch of stuff at you. Let's see whether it makes sense. So it's a bunch of discussion of dark mode and light mode. So really, what we want to say is, you can think of this as sort of type erasure. We want to say that I want to take a collection of things that, and I only care about the fact that they implement this trait.

[27:26] I sort of want to take an abstract notion of this trait. All right, so the challenge that the compiler is pointing out is in this case, where are we going to even start with this? All right, I think we need to talk about the sized first. So let's go to the sized trait. So the size trait has no methods. It is a marker trait.

[27:58] That's what is in the marker module. And the description just says, types with a constant size known at compile time. Now, most types are sized. Like if you create a struct foo, it's probably sized. Most types in the standard library are sized. In fact, there are very few types that aren't sized. So few, in fact, that every trait bound you have, even if it's just like a foo T, has an implicit bound of requiring that the type is sized.

[28:32] And to see why, think about what happens when, let's just sort of comment this out for a second. Let and comment this out for a second. I just want to get actually, I guess I can do this smarter. So let's sort of go back to our very simple strlen example in the very beginning, right?

[29:05] It's gonna be generic over some S that implements asterisk str. It takes that S. And it returns uSize as ref length. So imagine that something wants to call strlen. Well, strlen takes an argument that is that s. So it has to be past a thing. Like somehow it needs to be past that argument. Well, the argument that it gets past has to take up space on the stack or has to be passed in a register, either or.

[29:41] Which sort of means that the compiler has to make sure that there's sort of code in the resulting assembly that allocates the required space on the stack for whatever this argument is. And that requires that the compiler knows how large the argument is. If s here, I guess think of the concrete implementation, so strlen str. Here, this is just a, hmm.

[30:20] And let's go with the string implementation. So string is really just a, it's sort of two numbers and a pointer, right? It's the length of the string, it's the size of the allocation, and it's a pointer to the first character in the actual string on the heap. So it's size. The compiler knows that the size of this argument is three words, three. use sizes, if you will, right.

[30:52] And so we can generate the assembly code for this function and for calling this function trivially, because it knows how much space the arguments take up. You can imagine something similar, right, where if we were generic over the return type, it would need to know how much space to actually allocate for the return type on the stack. And so even though we didn't specifically say that s is sized here, it just is basically always a requirement that the type is sized. Because if it wasn't, the compiler wouldn't know how to generate the required code for it. Right.

[31:35] All right. So why. Why then is it compiling when we're trying to use this? Well, din high is really just saying anything that implements high, like just something that generates high without giving a concrete value. Because remember, we want this to be a slice of potentially like string and stir and whatever other types might implement this trait. And those are all different sizes, right? A string is two numbers on a pointer, a str is one number on a pointer, and you can imagine that we have some type foo that is like a gigabyte large as a struct or something insane, right?

[32:16] And we implement hi for it, and that is also something that we might wanna pass in here. So this slice doesn't have a size. It's just not, like if you, a slice is really just a contiguous piece of memory, right? Where each chunk is the same size. It's an array where all of them are the same size. But if we don't know the size of them, we can't guarantee that they are the same size. If I told you, if I gave you one of these, So din high here is not sized, right?

[32:47] Because it could be any type than once high, which could be any size. And I asked you, give me the fourth element. Normally in an array, because all the elements are the same size, the fourth element is just the pointer to the start plus like three times the size of one element, right? This is a pointer arithmetic to get to the fourth element. But if they're different sizes, you can't generate that code. And this is why it's saying slice and array elements must have a size type, because otherwise, the type just doesn't make sense.

[33:23] So how can we fix this? We really want to be able to do this. It would be insane if Rust didn't give you the ability to talk about things that implement a trait as a collection. And arrays aren't the only problem here, right? Even if we took, even if we wrote, what's a good example of this? Let's say we had a strlen2 here that took a like din asref str. It has the same problem, right?

[33:57] If I try to compile this, you see it says the same thing. Let me get rid of the other message. It says, the size for values of type din sRF str cannot be known at compilation time. Sized is not implemented for din as ref. Function arguments must have a statically known size. Borrow types always have a known size. And then it tries to give you a suggestion for how to fix it. But this is sort of the key insight again, that the compiler needs to know how large the type of an argument is.

[34:31] Otherwise, it can't generate the function call code. And so this is sort of like a fundamental requirement of the compiler that these types are sized. Does that make sense so far, like why this is a problem? Can you show us implementing sized? So sized is auto-implemented for any type that can implement it.

[35:04] So if you do like struct foo with no fields, it is sized. If you add a string in there, string is sized, so foo is sized. If you add another bool, this type is now still sized. Types are always sized if they can be. The exception would be if I did something like... And in fact, even if I did foo t instead of this holds a t, it's still sized because remember that there's an implicit requirement for every trait bound that it is sized.

[35:38] So there's sort of an implicit t sized here. And so that means the T is sized. So all the fields are sized. So therefore foo T is sized for any T. So you never implement sized yourself. It is only ever used as an auto trade. The issue is not stack size.

[36:12] The issue is not that it might not fit on the stack. It's that in order to call a function, right, just at the machine code layer or think of it as the assembly layer, right, in order to call a function you need to know when you call that function how much space do you allocate for the like stack variables of that function. We might include some of its arguments or on the caller side when you have to allocate the space for the return value, how large should that space be? Fundamentally, that just requires that you know how large the space is, because you can't generate the machine code for making that stack.

[36:49] There are like sneaky ways you could do this, but basically, the compiler, in order to generate efficient code, has to know the size of these things. Let's see. What things aren't sized? So we've talked about bear traits. So this is if I write pubfn foo, and I just say that I take a high.

[37:27] High here is a trait, and lots of things implement that trait, and they might all be different sizes. So this doesn't have a defined size. If I say impl here, right, impl is a shortcut for H. Hi. So this ADH is sized because we get a copy of foo for every concrete type. And for each of those copies, the size of the type is known. So if we use static dispatch here for monomorphization, this is fine.

[37:59] But if we just try to take like the trait itself, saying basically this function takes anything that implements the trait, this won't work because this is not sized. And this is equivalent to writing din hi. Like this is not sized. We'll talk in a second about how you make something like this sized. Um, the other example is something like, um, uh, if we go back to my, my struct foo, uh, if you try to have it hold a stir, uh, stir is not sized, um, because a string can be any size sort of, if you think about not the pointer to the string, but the string itself can be any size, uh, the same with like, um, This, just like a slice without a reference, is also not sized because you don't know how many elements there are.

[38:51] So it doesn't have a well-defined size. Those are the two best examples I know of, of things that aren't sized. And then anything that, in turn, contains those types. There's a lot of discussion in chat trying to explain the things that I'm about to explain on how we fix this and why you need references and stuff. I will get to it, I promise.

[39:28] Great. So I think roughly where we've gotten to so far makes sense, it seems like. So the question now becomes, how can we resolve the situation? We want to be able to take a, for our Sterling 2 here, let's call it Sterling Din maybe. We want to be able to have a method like this that doesn't get monomorphized. But this isn't sized, so what do we do? The trick here is to make this be a type that is always sized.

[40:05] And the way that we do that is by indirecting it through some type that is itself sized for any inner type. An example of this is a reference. So a reference is always the same size, it's just the size of a pointer, or in some cases two pointers, we'll get to that in a second. This does have a size. The compiler always knows how large one of these are, no matter what the type that follows is. Because this is just a pointer.

[40:40] The same would be if you have a box. right? A box, also just a pointer to the heap. And so once we do this, the size of this argument is now known, and we're fine. And this is in fact how you take something, take a trait itself without monomorphizing, is you place it behind some kind of pointer type. Like a reference, like a box, like an arc.

[41:13] The way this works in practice is that if you look at the definition of box, so it has magic in it, right? It's not magic, but it has a bunch of stuff inside of it. Basically, it just has a pointer. It's not quite true, but close enough. Box actually has this definition on it. And the question mark here means does not have to be. So it's basically opting out of the auto bound that gets added of everything has to be sized, saying for box, the T does not have to be sized.

[41:50] And that's why you can create a box of something that itself is not sized. And the reason this works is that when you create the box initially, you make an allocation that's the size of whatever you're going to put inside of the box. So let me make a main here that's going to exemplify this. At some point, I have to do box new of, say, string from hello.

[42:25] Right? And then I can say that now this is going to be a din as ref str. This should say x. And this should say str. And then I can call strlen din with y. So at some point when I created the box, I had to give it something with a concrete type. And at that point, it allocated on the heap space for that type.

[42:57] But the box is still of a known size because it's just the pointer. When I turn it into a box for this, it's still just a pointer conceptually. even though the thing it points to might have an arbitrary size. But the actual argument that we pass to this function does have a size, and therefore we can generate the relevant code. Does it make sense why indirection through a type like this where the indirection type size is known? Does that make sense?

[43:37] We'll talk about combination of traits too. Let's see. I promise we'll get to multiple traits. Can't you just put BoxedInAsteroidStir directly on X? Yeah, so you can do this too. AsteroidStir. That's also fine. But even so, you still had to provide a concrete type to Box New that was sized.

[44:16] When should we use box over references? Like when do you choose this over this? There's no hard and fast rule there. In general, the advantage of box is that it's static. So you can keep using it even after the stack frame of the caller goes away. So it's the same as when do you choose box over references normally. Can I also then give the function a reference to the stack? Yeah, exactly.

[44:47] So you can also do, let me do that down here. So I can totally do, and then Sterlendyn, why? Right. So this, let's say I have a din2 that takes this, and this can call din2.

[45:25] Why is this complaining? It's because box has an asterisk method too. That's why the double asterisk is needed. Yeah, so you see, I can do the same for something that's on the stack. I can create a sort of go through a pointer in direction here and then pass it to something that takes a referenced in.

[45:59] And in fact, I think I can even do this. Yeah, that's fine. It's not terribly important why that doesn't work. So what we just constructed is known as a TraitObject. It is an object that only has the property that it represents a trait. So this is what TraitObjects are. They are things that only behave as some underlying trait.

[46:35] This is a TraitObject, and this is a TraitObject. It doesn't matter what the wrapping type is. Box is kind of a pointer type. Yep, box is a pointer type. Can I convert a trait object to its original concrete type? I'm going to go with no, but technically yes, sometimes. But in general, no. You can think of it as, this is essentially type erasure.

[47:08] You can technically go back through like unsafe transmutes and stuff, but in general the moment you turn it into a trait object You erase the knowledge about what type it used to be But yeah, there's like some magic around unsafe and some magic around the any trait that you can use. But in general, you should ignore that. Also note that when you do this, you only retain the ability to use this trait. You erase all other knowledge of what the concrete type was.

[47:39] So the only thing you can do on a boxed in ASRF stir is call ASRF on it, nothing else. Same thing here. And we'll get into why in a second. All right. So this raises an interesting question. Let's take the example, let's make this the two and this the one, and just swap these around so this still compiles. Let's now think about what actually happens when the compiler has to generate the machine code for this function.

[48:15] At some point it has to actually do the compilation and produce assembly code that can in turn be turned into runnable machine code. So S here is some type that implements Sref. In fact, let's go back to our high trait. That's going to be a little bit nicer. So let's go back to here and let's say that I want a sayHi which takes a dinHi, returns nothing, and just calls Hi Right? So this is going to be, this takes a trait object for the Hi trait But when the compiler generates the code here, it doesn't know what type s is Right?

[49:01] It's just a trait object. It's really just a pointer. So how does it call the high method? Remember, in the generic case, static H. In this case, we actually get a copy of this for each concrete type.

[49:37] So really, this turns into this. And for this concrete implementation, generating the machine code is trivial, because this is really just like an assembly call to whatever it is, to this line, to line 6. It's not actually line, it's memory locations in the binary, but you get the idea, right? That the compiler knows statically at compile time where to go here.

[50:10] For the dynamic case, though, what do we call? We don't know that this is a str or a string, right? So we don't know whether to generate the address of this, the address of this, or the address of something else entirely. So what machine code does this turn into? Well, this is where we get into dynamic dispatch and V tables or virtual dispatch tables. So the trick to constructing a trait object is that it's actually not quite true that the reference of the box is just one pointer wide.

[50:48] It actually carries a little bit of extra information about the type that is pointed to. So here, let's go back to the, back to the the Rust book. So the Rust book has a chapter on dynamically sized types and the size trait. This is under the advanced type chapter. And what it's talking about is, in fact, it doesn't even talk about as much as we wanted to talk about. Here.

[51:22] Let's use the Rust reference instead. So the Rust reference on dynamically sized types says, most types have a fixed size that is known as compile time and implement the trait sized, like we've talked about. A type with a size that is known only at runtime is called a dynamically sized type, or informally an unsized type. And this is the slices and trait objects are two examples of dynamically sized types. The reason why this is only known at runtime is, at compile time, we don't know what type this is gonna be. It's only at runtime that we'll know.

[51:54] And we can, to make this a little bit more concrete, imagine I have a main function where if rand, I don't have a random number, random is four. If random is four, then say hi of this, Otherwise, say hi of string from world. Right?

[52:30] And let's imagine that random was more random than 4. You don't know until runtime. Let's say this was read from the user. At compile time, you don't know which actual type is going to be used here. It's only determined at runtime by some input that can't be predicted at compile time. Right? So that's why this is determined at runtime. And it says, pointer types to dynamically sized types are sized but have twice the size of pointers to size types.

[53:09] So pointers to trait objects also store a pointer to a V table. And this is where we get into what is a V table. Well, when you have a trait object, something like at din pi, what actually gets stored in the reference is one, a pointer to the actual concrete implementing. implementing type, and two, a pointer to a V table for the referenced trait.

[53:48] So then what is a V table? So a V table or a virtual dispatch table is a little data structure that has pointers to each of the methods for the trait for the type. So in the concrete case of the high trait, so let's say we have a din high, the V table is going to be sort of you can think of it as a high V table struct that only has one member, which is high, which is a pointer to an Fn, an Fn actually, that itself takes a pointer to whatever the T is.

[54:45] So basically, a different V table ends up being constructed for each concrete type turned into a trait object. So when we start out with, let's say that we have a stir, and we want to go to a din high, what actually gets constructed is a let's say we have a um Well, number one becomes a pointer to the str.

[55:16] And number two becomes a high Vtable, where high is str as high, high, and a pointer to that. When you make this conversion, the compiler knows that it has to construct this Vtable, and it sticks the address of that Vtable inside of that reference.

[55:48] So this reference contains two things, the pointer to the actual type and the pointer to the Vtable that the compiler generated during this particular conversion. So there'll be one such Vtable for each type that gets turned into a TraitObject. And so now when the compiler tries to generate this code, what it actually generates is like s.VTable.High s.Pointer.

[56:23] And so if someone passed in, say, a string instead, it would have a different Vtable. So the s.Vtable would be a different pointer. So in this case, this would be where is str high? Like line 6, right? So this would be a pointer to line 6. But if we instead went, I'll stop for questions in a second. If this instead went from a string to a dyn high, It would be a pointer to the string and string as high, which is this method up here on line 12.

[57:06] So in other words, this code that gets generated will work regardless of which type is passed in because we indirect through the V table and each type has its own distinct V table. All right, that was a lot to throw at you at once, but hopefully it wasn't too bad. Let's see.

[57:45] Are the V tables themselves statically built at compile time, or are they also allocated dynamically? The V tables are... The V tables are built at compile time, they're built statically. And so in general, the second part of the... So this is what's known as a fat pointer or wide pointer, because it has two pointers in it, not just one. So anytime you see this, it's actually a wide pointer. And in general, the second pointer in there will always be known statically, because it's determined by the original construction.

[58:23] of the trait object. The reason I say generally is because you technically can construct it on the fly. There's nothing in the calling here that requires that it was known statically. So you could imagine manually constructing a vtable. And this is used, we'll actually talk about that a little bit later. Refster also contains the length of the string slice.

[58:56] Yes. So in general, this will actually be this. So it's not a pointer to the actual string. It's actually a pointer to the str reference, which itself holds the length. Can we debug print the Vtable struct somehow? I don't know of a way to get the compiler to print its Vtable struct, but it's basically just this.

[59:33] It just, there's a member for each method of the corresponding trait that this is a trait object for, where each member is... Each member is a corresponding method, and the value is the pointer to the implementation of that method for the concrete type. Then why are trait functions that don't take self not object safe? Couldn't the compiler just generate an fn mute self that doesn't use self?

[1:00:08] We'll talk about that in a second. Does it construct a new V table every time we create an instance? No, the V table is generally statically constructed for the type. It doesn't get constructed dynamically. Are identical V tables detected? No, there's no deduplication of these. And in fact, they are guaranteed to not be duplicates.

[1:00:43] If you implement a trait for two different types, then the implementations, even if they contain the same code, are still distinct locations in the source code and in the resulting binary, and so would have different addresses. Trait objects of more than one trait we'll get to in a second. So box din is a thin pointer that points to a wide pointer that points to the object. No, if you have a box din height, that box itself is a wide pointer.

[1:01:22] So box is a little bit of a special type. Actually, it's not that special. It's just that box internally contains a mute dhinhi. And the Rust compiler knows for references and pointers that if they are trait objects, they're actually width 2. So box isn't special, but pointer types are. So box.dynhi is itself wide. You don't end up with an extra indirection. Yeah, we'll talk about nightly APIs for trait objects too.

[1:02:13] All right, so I think we're now at a point where that roughly makes sense. So there are a couple of reasons why trait objects are a little bit more constrained than being fully generic. So, for example, let's imagine that you wanted to have a... hubfn baz that took an s that is din, let's say, hi plus sref stir.

[1:02:58] And we're going to do s.hi. And then we're also going to say, let S is S dot S ref. And then we're going to do S dot high again, because we know that strings themselves implement high. I guess maybe that's confusing. Maybe I should just do len. The compiler here said, oh, it's ambiguous. All right, let's get rid of the ambiguity. It's not really relevant to the discussion.

[1:03:33] It still won't let me do it, why not? Do I have to do this maybe for it to not be ambiguous? No, all right, I'm just gonna, let's pretend that the syntax worked for a second here. So basically I want to say that I want a trait object of two different traits. This won't actually compile and ignoring the parsing error for a second, there's actually a bigger reason why this won't work, which is, In order for this to work, we need to know both where the high method is and where the asref method is.

[1:04:18] But those are contained in two different vtables. One is the vtable for high for the concrete type, and one is the vtable for asref for the concrete type. And so what we'd actually need is not just a two-wide pointer, but a three-wide pointer. A pointer to the data, a pointer to the vtable for high. and a pointer to the V table for ASRF. And that's possible. There's nothing that's sort of inherently impossible by that, but it would mean that as you add more traits, the size of this reference just keeps on growing.

[1:04:55] And that's probably not what you intended. And you might go, well, can't the compiler just generate a V table for the combination and then pass that in? That is something that in theory it could do. The Rust compiler doesn't currently do this. I don't know of a proposal. to do it. Part of the reason is because you can get around this by saying pub trait high azref and it requires that the type is both high and azref str with no methods of its own.

[1:05:28] And now I can do this. Right? Because now there's only one Vtable, and that Vtable is high ASRF, and the compiler knows when it has to generate the Vtable for this trait, that includes all the methods from both of these traits. And so this Vtable is going to be larger because it is going to have both the high method and the ASRF method. And so I think part of the reason this hasn't landed in Rust itself is because you can opt into it yourself. And by not automatically turning the plus into a larger V table, you basically tell the developer that this might not have been what you meant, but if it is, you can do this thing instead.

[1:06:12] I agree the compiler error here probably been better, right? Some in Esteban Cooper. That maybe we could sort of inform... people that they can generate their own trade here. I think it's someone wrote I think it's I plus s ref.

[1:06:52] Stir, let's see if that's true. Yeah. Okay. So, so that is the, the, the way to get the right compiler error, which is only auto traits can be used as additional traits in a trait object. Whereas here you have an example of two different traits that are, neither of them are auto traits. We'll talk about that in a second. And here it does actually give the suggestion we talked about, right? Consider creating a new trait with all of these as super traits and using that trait here instead. And it also points out that auto traits like send and sync are fine.

[1:07:27] And basically the idea here is that for marker traits, like if I want to say high plus send, send doesn't have any methods. So it's fine for the V table to be empty. And therefore we don't need to store that additional part of the V table because there aren't any methods in it. So that's why it's okay to have additional traits with no methods. I don't think you can use your own. Like if I did a Fuchs trait and I said this plus Fuchs, I don't think that'll work.

[1:08:00] But there's been some proposal of having a marker annotation to declare a trait as never having methods. But that's not something we currently have. So at least for the time being, this is the way that you should do it. Great.

[1:08:34] All right. So that is how this works with combinations of traits. But that's not the only example where trait objects are a little bit limited. So the other one is, let's imagine that for high, we added a, actually, let's start with saying that we added an associated type. Let's call it name. And we don't actually use it for anything, we just add one. The code already doesn't compile. Why doesn't it compile?

[1:09:05] Well, the value of the associated... Oh, that's the implementation. Let me do that. So this is going to be type name equals unit. Just going to use that for both of them because we don't actually care about the type. Yeah, so here it says the value of the associated type name from the trite high must be specified. So it says here where we take a din high, we actually need to specify the associated type.

[1:09:39] We can't just say we take any high regardless of what its associated type is. And the reason here is because that information can't be captured in the V table because this is a type. It doesn't have an address in the binary. It doesn't have anything we could stick in the V table. And therefore, this won't work with a trait object directly. Instead, what you would have to say is I take a high where name. is this. And I think we need to do the same down here.

[1:10:15] And then that works. Because now we have a V table specifically for anything that implements high where the associated type is name. So that's fine. Let's undo this because it's not a very interesting change. The other, perhaps more interesting case is, let's say that we want a... What are we going to call it? We're going to call it, like, weird. We're going to have a weird function that does nothing.

[1:10:48] No one needs to implement it. And you see that this also does not compile. Error in cargo check. Let's make this a little bit smaller so that hopefully it's a little easier to understand. Hopefully it's still readable. Ooh, that's very verbose. Let me comment out the combination trait bit just to make the errors a little nicer. Alright, so this says the trait high cannot be made into an object.

[1:11:24] So when we say din high, basically it's telling us that the high trait is not object safe. That is, it cannot be turned into a trait object. And it says for a trait to be object safe, it needs to allow building a V table to allow the call to be resolvable dynamically. So this is what we've been talking around through so far. And in particular, here it says the trait cannot be made into an object because the associated function weird has no self parameter. It doesn't really talk about why that's necessary though. But let's try to work through it.

[1:11:56] So again, let's say that down here in our sayHi, right? We now try to call s.weird. So imagine what would the compiler do if we wrote this code? Well, we can't really write this code, right? Because weird doesn't take self. It doesn't take a pointer to anything. And we can't just like randomly construct a pointer to it because that would mean that we need to have a valid instance to it to have a pointer to it.

[1:12:28] So this is really just saying like, then hi, like colon colon weird. which I don't have to tell you seems weird because which type are we calling weird on here? There is no, like nothing here specifies which actual weird implementation we want. In this particular case, because it provides a default, you might think it's not a problem. Well, what if there was like an implementation of weird for string?

[1:12:58] that was different from the one on the trait, which is allowed, right? You can override a default implementation. Well, how would this know whether to call the one for str or the one default for the trait or some entirely different one? It can't be in the V table because there is no S here, right? The weird method doesn't take itself. It's not associated with any given instance of any type. So this just doesn't work. It's not a meaningful thing to say.

[1:13:32] But what if you really wanted this? Like you wanted the weird function to exist, but you're like, I don't care about calling this through a trait object. I only care about the high thing. through a trait object. So I want high to be trait object safe, but if you have a trait object high, I'm fine if you can't call it weird. So you can do this. this.

[1:14:09] And let me go back down here, have the speed in high again, s dot a. So. What we're saying here is that the weird function requires that self, that is the type that implements the trait, is sized. And we remember that traits aren't sized. If you just have like din high, that's not sized. It's only sized if it's behind a pointer type.

[1:14:43] So this is basically a way to opt out of the V table is the way that you can think about it. It's saying this function shouldn't be placed in the V table and crucially shouldn't be callable through a trait object. What this means is in here, let me get rid of the static versions because they're just in the way. What this means is now the code compiles just fine. I can call hi, I can make a trade object for it. But if in here, in fact, I can go even further and say, let's say that this did have a self, but I wanted to opt out.

[1:15:22] then this still compiles, I can still make a trait object for it. But let's say that I try to call weird in here. the compiler is gonna tell me the weird method cannot be invoked on a trait object because the method has a size requirement. And so this is the way to opt out for any given function from having it be included in order to make sure that the trait remains object safe. You can also say that the entire trait should not be possible to turn into a trait object by saying where self is sized.

[1:16:01] So if you do this, you're basically disallowing using this trait as a trait object. It's rare that you see this in practice. Usually the trait will, like the trait just isn't object safe because of the methods in it. Opting into disallowing trait objects is rare. Sometimes people do it for... backwards compatibility reasons. Like if you know that you might add non-object safe methods later, you might add this proactively, but it's pretty rare.

[1:16:36] All right, do the restrictions so far make sense? Does the associated type problem also occur with static dispatch? No, it doesn't. And the reason is with static dispatch, because it gets monomorphized, you actually know the concrete type for any given function implementation. s colon colon weird could be possible.

[1:17:10] So this is back when we had the fn weird, right? And let's say we also had an override here. And now let's say you wanted to be able to like, let's say we added like special syntax like this saying for the type of s called the weird method. you could imagine that weird got included in the vtable for the trait object, but it knows to not call it with a self argument. The challenge here is that this is sort of odd.

[1:17:45] If you require an instance of the type anyway in order to call it, then why doesn't it just take self? The traditional example of this is that weird is actually called new or something like new, right? Where it doesn't, if you already have an instance of the type, you wouldn't need to call the method in the first place. It would just take self. So I agree like something like this maybe could be possible. I think in practice, it's just not usually very useful.

[1:18:19] And that's why it hasn't been a priority. There might be a deeper reason why it's not added to. I'm not sure. um um does where self colon sized also disallow implementing the trade for concrete dsts um You know, that's a good question. So the question is basically, if you have where self is sized, can I implement high for box din as ref stir?

[1:18:58] for example. I believe I can. The reason I say this should be possible is because, yeah, this now won't work because it can't be a trait object, but you can still have this implementation, I believe. Why does this? Oh, right, because it's a box. So we need to have the double sref. This is fine because this is not a dynamically sized type.

[1:19:35] Again, when you wrap it behind a pointer, it now has a size. It's not dynamically sized. So it doesn't prevent that, even if you have self-sized on the trait. The associated type restriction feels weird because the point of associated types is that only one exists for any given concrete type. So shouldn't the V table know what the associated type should be? Like, it can't have a pointer to the type, but the implementation of the trait should know what the type is when it's compiled.

[1:20:07] Yeah, so the problem is that the type is erased. All that remains is the V table. And so you can't tell from the V table what the concrete type used to be. There is an exception to this, which is the any trait. So the any trait has a method that returns... turns a descriptor of the type of the concrete type that it used to be. If you didn't follow that, that's fine. Ignore it. But basically, there are some ways to sort of finagle around this. But basically, trait objects are type erased.

[1:20:38] Like you don't get to keep information about the type it used to be. Oh, you meant type such as str or u8. No, you can't do that. Self has to be sized when you have where self is sized. There's one other restriction that you get with TraitObjects, which is that the methods cannot be generic. And for this, rather than sort of keep working on our weird high trait, I'm actually gonna go to the standard library and look at the fromIterator trait.

[1:21:16] So the fromIterator trait is something that's implemented by Vec, for example. This is how collect works, is that Vec implements fromIterator. And when you have, well, So if we look at iterator collect, I guess is the best way to do it. Collect on an iterator requires that the thing that you collect into implements from iterator. So that's why you can have an iterator and collect into a vec, it's because vec implements from iterator. The from iterator trait is a little weird though. The A type of the trait is the type of the items of the iterator.

[1:21:55] but you also see that the from iterator type itself takes a T. And the T here is the type of the iterator, right? Cause it has to be vec, for example. It doesn't care what the iterator is. It can be, it can, you can construct a vec from any type of iterator, as long as the, well, you can create a vec T from any iterator where the item is T. This arguably should be called I for iter, but it's not terribly important. Here, where a is the sort of thing that you'll end up with a vec of.

[1:22:30] So if this a was, say, bool, you would end up with a vec of bools. And the t is the type of the iterator, which might be something like, I don't know, like a HashMap Intuator or whatever that type ends up being. This poses a problem for a Trait object, though. Let's imagine that we try to write code against this. So I'm going to erase this for a second. In fact, I'm going to write a new one. erase all of the remainder of this file. Then I'm going to have like, what are we going to do here, let's do collect.

[1:23:09] Standard iter from iterator, we're going to take a from iterator of bool. And we're going to return a vec of. And I'm going to do s dot collect. Ooh, what did I do? I did something weird, didn't I? Great. So this seems like it should be fine, right? I take anything that can, I take.

[1:23:42] Well, actually, this is weird for a number of reasons. Maybe fromMeterator is a bad example here, because it doesn't take self either. So it actually requires self to be sized anyway. Extend is a better one. Let me dig up extend here. Great. So we're going to use extend instead. and it's going to have to take a mutant. And so we're going to do that mute v is back new, then we're going to do v dot extend.

[1:24:18] Actually, we're not even gonna do that we're going to take this is going to be the V, we're going to do v dot extend, and we're going to give it just it are once true. So we're going to just extend it with a Extend with a single bool, add true. So we take in anything that can be extended with an iterator of bools. And then we try to extend it with an iterator that yields a single bool.

[1:24:49] So we're just gonna add true, we're gonna append true to whatever thing we get. And here too, it tells us the trait extend cannot be made into an object because extend is not object safe. And if we look at extend, that doesn't immediately make sense from what we've seen so far. Right? So again, it's generic over the type of the items of the iterator. That's fine. Extend takes self. So we do have something we can stick into the V table. And given an instance, we sort of know how to call this method. But again, notice that it's generic over the type of the iterator.

[1:25:23] And this is where it gets really weird. you can imagine the like inside of vec, right, there's going to be imple t, extend t for vec t. And it's going to have this implementation. I'm going to go go ahead and call this I because I think it's more helpful. And who knows what's going to be in here, right?

[1:25:58] Yes, just to get rid of that warning. Uh, I'm going to do this. Um, I guess be a little bit more helpful. My vec. Like this implementation is going to exist somewhere in the standard library, right? Except just for vec instead. But this method is generic. So we know from the monomorphization discussion that actually at compile time, we don't end up with a single extend.

[1:26:35] We end up with multiple copies of this method. Right? We end up with like an extend rule that takes... Now, an extend, I guess, HashMapIntoIter, which takes a standard collection HashMapIntoIterator. Right? And in fact, even more than that, we're actually going to end up with, because the whole impl is generic, we're actually going to have this.

[1:27:13] That is the actual method that gets implemented. or get sort of generated by the compiler, assuming that someone tries to extend using a HashMap iterator of bools. There is no one extend. There is one for every combination of iterator and item types. So what gets put in the V table? We've nailed down that we want to extend bool.

[1:27:44] So that's good, right? So there's only, we don't have to consider the T up here because we've already chosen that T. But for extend itself, we really, in the V table, really needs to have a pointer to extending for this iterator type over bool. but that's not expressed in the type of the function. And we don't even have a way to express it. Right, you could just sort of imagine like where, like these implementation of extend is standard iter one spool or something super weird like that.

[1:28:26] But the way that it's written, nothing here says that we want the Vtable to point to the extend implementation for a standard iter once. And therein lies the problem. When the compiler tries to generate this code, there is no pointer to the appropriate implementation of extend. Therefore, the V table can't be generated. You can't generate a V table for dinExtend because it would have an infinite number of entries, one for each possible implementation of extend.

[1:29:02] And so therefore, the answer is just dinExtend cannot exist. You cannot create a trait object for extend. All right, does that make sense? That's a somewhat intricate explanation, but hopefully it all sort of ties together here. Um, could Rossi add a monomorphized version of extend extend for each T it's called with to each type that implements extend that's tempting, but it's not always possible, right?

[1:29:36] So imagine that you're compiling this code, but, um, I mean, even just for the standard library, right? Like the standard library has a bunch of uses of extend, but in crates that depend on that crate, they might call extend with even more types. So the size of the V table, like when you compile the bottom most crate, if you will, like the standard library, essentially, that would mean that the V tables for din extend in the standard library is different than the V table for din extend in crates.

[1:30:12] other crates further up because there are more possible iterator implementations that you might want to use. And so you now would end up with lots of different vtable implementations or lots of different vtables for dinExtend. And that's like it would be a combinatorial explosion kind of problem. And it would also mean that you can't pass a dinExtend from the standard library to a thing that takes dinExtend in a crate further up because their vtable types are different. All right.

[1:30:54] So this is the reason why you can't have... In order for a trait to be object safe, it needs to... not have generic methods. It needs to, all of its methods need to have a receiver that includes self. And there's another requirement, which is that the trait can't have a type that returns self. So if we backtrack a little here and say clone, and we wanna take a thing that is didn't clone, and we're just gonna, call clone because it's the only thing we can do with a din clone.

[1:31:37] Right? If you have a din clone, you can literally only do the things that the trait lets you do, and the only thing clone lets you do is clone. So this says the trait clone cannot be made into an object. This is now an error that we've seen a decent amount. The reason why you can't do this is because the clone trait, right, has a FN clone that takes self and returns self. Alright, so let's say I say let x is v.clone. What's the size of x? Didn't clone is just any type that is clonable.

[1:32:16] And it's supposed to return self, like not the reference. So it's not supposed to return a reference DynClone. It's supposed to return self given a reference. So that sort of means that it should return DynClone because that's what self is here. Because we've erased the concrete type. But DynClone isn't sized. So it would mean that the return value of this method isn't sized. And the return type of a... function must be sized for us to generate code for it.

[1:32:49] Therefore, this can't work. So you can't have methods that return self for a trait to be object safe. And that's why you can't do clone. Now, there are some cases where you have a trait where, as we talked about with high, you might have some methods that are object-safe and are still useful on their own, but you have a bunch of other methods that would make the trait non-object-safe, but you want to include them for types that aren't going through a trait object, just because it's convenient.

[1:33:23] And in fact, a good example of this is if we look at the iterator trait. So the iterator trait... right has the associated type item that's fine it has next and next is object safe but it also has a bunch of methods like chain which is generic it has enumerate which returns self it has By ref, which returns mute self.

[1:33:56] It has collect, which depends on from iterator, which we already know isn't object safe. So how can iterator be object safe? Because it is. If I say it here, and I say I want to take a din iterator where item is bool, we collect. Oops, iterator. Well, I can't call collect because this method cannot be invoked on a TraitorObject.

[1:34:30] But I can call next. I'm allowed to call next on this. Mute, otherwise it doesn't work. That works fine. And the way that the iterator trait has achieved this is that if you look real carefully, you'll see that, if I actually go to the source of the iterator trait, you should see this, you just find here.

[1:35:03] So count, for example, which consumes self, right? So it's not allowed to go behind a reference, which would make it sized, has where self is sized. If you scroll down to last, which is the same, self is sized. If we look to chain, you see the chain, which is generic, so normally would make the trait non-object safe, has where self is sized. And the reason for this is you can basically, this is the same thing we did for the weird function, right? You can use the where self is sized bound to say ignore this function for the purposes of using this trait as a trait object.

[1:35:41] Basically, don't try to put it into the V table. What that means is if someone has a trait object, they can't call the method. But if they don't have a trait object, if they actually have like a vec intuitor or like they have the concrete type, then they can call this method. And so this is a way to have a trait that has some methods that are nice to have, but wouldn't be object safe without making the whole trait object not object safe. Um, can the receiver be anything that includes self or does it have to be ref self or mute self?

[1:36:16] Um, so the rules for this are actually, uh, where do I have this? I have it open somewhere. Give me a second. Here. So this is from the Rust language reference on object safety. And in fact, by now we've covered most of these things. All the super traits must also be object safe, right? Because we construct a V table from the union of all the super traits. Size would not be a super trait.

[1:36:47] So that is, if we require self colon sized, it's not object safe. Must not have any associated constants. This again is because. you don't have anywhere to put the constants. Theory, maybe you could put them in the V table, but now the V table becomes really large. And also the values in the V tables are no longer all like function pointers. They might be arbitrarily sized things. All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable.

[1:37:19] So dispatchable functions require that they don't have type parameters, so they're not generic. They have to be a method that does not use the self type, right? The concrete type, except in the type of the receiver. So this is we can't have something that returns self, for example. It can't have a receiver with anything but the following types, right? So it can be a reference to self, it can be a mutable reference to self, it can be a box self, RC self. ArcSelf or PinSelf, PinToSelf rather. So anything that's behind a pointer, basically anything that can take, anything that can turn something that's not sized into something that is sized.

[1:37:55] And you can see that explicitly excludes where self is sized bounds so that you can have an object safe trait even if some of the methods aren't object safe. This is the non-dispatchable functions. Um, should library writers always consider adding where self is sized to non-objective methods, just in case someone downstream wants to use it as a trait object? I think yes. Um, It depends a little bit on whether your trait is even usable.

[1:38:28] So if your trait isn't usable as a trait object, like think of clone, right? Then sure, you could add where self is sized to the clone method so that people could create a trait object clone, but they wouldn't even be able to call the main function of that trait. So it's probably not worthwhile. But I do think that in general, if you have a trait where it is useful, even if you... could only call the ObjectAve methods, then it might make sense to opt out for the other ones so that the trait overall is ObjectAve.

[1:39:14] Did iterator last have the sized restriction? I think iterator last does. Um, the reason why last, uh, has where self is sized, you can't see it here. It gets hidden by rust doc, um, is because it's receiver. It doesn't go behind a reference. It consumes self, uh, which means that it takes self, um, and self is a din iterator, which is not sized and function arguments must be sized.

[1:39:47] Therefore last can't be called through a trade object. There's one more thing I haven't told you. Well, there are many things I haven't told you, but there's at least one when it comes to trait objects, which is that there's a little bit of a secret with trait objects. So let us say that I have pub trait. Actually, let's do this. This is a, drop is actually object safe.

[1:40:19] You might think that it's weird. Like if all you can do with an object is drop it, then is it really that interesting? It turns out this is useful in a couple of situations. Like I know Crossbeam does this, for example, where you want to do garbage collection, but you don't want to drop objects immediately. You want to like stick them in like a linked list or something and then periodically go and collect all the garbage. Because you want to store lots of potentially different things in one type, you need TraitObjects. And so it just stores mute in drops, or I think technically boxed in drops, but same effect.

[1:40:56] You can't actually do anything with this. But here, when v goes out of scope, dropDrop is called through the btable. This should make you go, wait a second, because let's go with our sayHi. We take the dinAsRef.stir. Or actually, let's even go with boxed.

[1:41:30] It's better. What happens when s goes out of scope? Think about this for a second. We get a box, so we have a memory allocation on the heap. We might use that in here, might call s.asref, which could be high, whatever. But then we drop s when this function returns. But when we drop a box, we have to free the memory. But this is a trait object, so the only method it has is asref.

[1:42:06] The answer to this is every Vtable includes drop. You can sort of think of this as like an implicit drop here, but in practice, the Vtable for any TraitObject includes a pointer to the drop function for the concrete type, because it's just necessary. It also technically includes a little bit of extra information. It includes the size and alignment of the concrete type. The reason those are in there is because for something like a box where you have to deallocate the memory, that information is necessary to pass to the allocator to do the deallocation.

[1:42:44] And so every trait object includes the V or the V table for every trait object includes the methods for the trait plus drop plus size plus alignment. Normally, you don't have to think about this, but it's just worth knowing while we're on the topic. To shift gears a little bit, so far we've only really talked about trait objects, but there are other types that aren't sized. So for example, we know that din trait is not sized, but u8 is also not sized, and str is not sized.

[1:43:20] This one gets turned, when you place it behind a reference or a pointer, gets turned into a tuple of a pointer to the data and a pointer to the vtable. This one, if you make it sized or put it beyond a pointer, also becomes a wide pointer, where one is a pointer to the data, but the other is just a u-size, which is the length of the slice. And same thing for str, as a pointer to the data and a u-size of the length.

[1:43:57] So this is why, if you try to write a function foo that takes a u8, the compiler is going to yell at you and say that the size for the value of type U8 is not known. Because U8 this is just saying an arbitrarily long list of U8s, which is not sized. Therefore we can't call the function with it as the argument. Same as if you try to return just a straight up U8 sequence, right? If I had a bar, which returned a U8.

[1:44:33] Um, it also complains. Oh, uh, is it even going to let me do that? There we go. I constructed the type. So here it says the same thing. The size for the value of type U8 cannot be known, and the return type of a function must have a statically known size. So this is the same problem. And here too, the way that we go from something that isn't sized to something that is sized is we place it behind a type that can sort of mask the uncisedness, which you do with a reference, or you can do it with box.

[1:45:14] So you can also do box of this. I think I'm allowed to do this. Great. So this is fine because it's now sized. The size of it is a pointer that is wide, where one part is the data and the other size is the length. Um, and the compiler then knows that when you access, uh, this type, it knows to sort of deconstruct the pointer to get the length.

[1:45:51] Um, same with something like box or, or raw pointers for that matter. And same for string. So these are a little bit magical. There's been some work on trying to standardize this. So currently the sort of dynamically sized types are a little bit special in the compiler because you need to know whether the pointer is sort of wide or not. So it's fairly hard to sort of deal with unsized types yourself. Like if you wanted to implement box yourself and take a type that wasn't sized, It's possible.

[1:46:27] It gets pretty annoying once you get into casting and allowing trait objects and stuff. But there was recently an RFC that landed. RFC number 2580. which talks about adding a generic API for manipulating the metadata of fat pointers. So this lets you do things like say what the type of the second part of the fat pointer is. Right. So in the case of in fact, we can scroll down here a little and look at a DIN trait now becomes a pointy where the metadata is DIN metadata.

[1:47:09] And we're DIN metadata. is a pointer to a Vtable that represents all the information such as type size, type alignment, a pointer to drop and place, and a pointer to all the methods for the type simplification of the trait. So exactly what we just talked about. Similarly, you could imagine that this pointy trait would be implemented for something like a U8 slice without the reference, where the metadata would be a U size that is the length of the thing.

[1:47:44] This is still very much like new and experimental. I do recommend you read through this RFC. It's really fascinating if you want to learn more about this. It has things like the trait alias thin, which is any type that implements pointy where the metadata is empty, which would be anything that doesn't have associated metadata in the pointer, so anything that is a thin pointer and not a fat pointer. And it has essentially methods for introspecting the metadata of a pointer, so that you can do things like actually look at the Vtable.

[1:48:16] There was some questions about this in chat earlier. This RFC would actually let you introspect that information and crucially construct Vtables on the fly. So you could have one that isn't known at compile time, but you build at runtime. And in fact, this already is something that exists one place in the standard library, as far as I know, which is for wakers in sort of the land of async. So the waker trait, we're not going to go too much into detail, but the waker trait, which I'll show you here.

[1:48:48] Um, the waker that's I'm lying. I mean the wake trade, uh, awake, not the wait, the raw wakers. Oh, there isn't a trade for it. That's why, um, let's go show you context actually. So context gives you a waker. Waker is a struct that has the methods wake, wake by ref, willWake, and fromRaw, and you can drop it and clone it.

[1:49:24] But in practice, waker is really generic. It's just that it isn't generic when you look at it. But inside of a waker is a raw waker. And a raw waker, if you look inside of it, is a data pointer and a vtable pointer. So it really is a data pointer. is dynamic dispatch but in sort of a hidden way and the vtable is a raw waker vtable and a raw waker vtable you construct by giving the function pointers for the clone method, for the wake method, for the wake by ref, and for drop.

[1:50:03] And so it's basically a manually constructed Vtable that gives you dynamic dispatch through a type rather than a trait. I'm not gonna go into too much detail of this, but I just wanted to show it as like an example of a manually constructed Vtable in the standard library. Is there anything more I wanted to talk about from here? I don't think so. All right, let's do questions because I've rented for a little while.

[1:50:38] I thought a reference to U8 had a start pointer and an end pointer, not a length. I think it has the length. It doesn't, the two are basically equivalent. You might be right, I forget. In fact, I wonder whether this reference says. Yes, you see, this RFC also deprecates the Trait object. stuff that exists in Nightly, because this is a replacement.

[1:51:11] Pointy trait, thin metadata, from raw parts. Where is the definition of... Oh, it doesn't actually give. Yeah, I was hoping it would say here what the actual associated metadata type is for slices, but I don't see it.

[1:51:42] I think it's just the length. Can we make our own types dynamically sized types? Sort of. So you can write this. foo here is now not sized. In fact, you can add more fields. You can't add a field after though. After this is not sized, right?

[1:52:14] So if I tried to do this, it'll tell me the size for values of u8 cannot be known at compile time. Only the last field of a struct may have a dynamically sized type. Change the fields type to have a statically known size. borrow types always have a statically known size. So what this is getting at is, if it's the last field, then think back to the argument I made very early on, right? If you have a non-size type in the middle here, and I asked you, like, if I want to look up like foo.x, and you only have a pointer to foo, how do you get a pointer to x when the type in the middle can have an arbitrary size?

[1:52:54] And the answer is you can't. You don't know how to get the address of x because t is arbitrarily sized. But if it's at the end, then it's fine. You can statically know the offset of f, the offset of x, and the offset of t. And the only information that's needed in order to make this sized would be the length of the last field. And so you are allowed to construct a type like this. This type is now not sized. But if you have an at foo, then that type will be sized by storing the pointer to the foo alongside with the length of t.

[1:53:34] So you can create your own dynamically sized types this way. Is box U8 the same thing as a vec U8? So this is if you have a box of a U8 slice, not behind a reference, is vec U8. They're not the same. So no. I guess let's do this.

[1:54:05] They're not the same. They feel the same, but they're not the same. Oops. Evacuate can grow. So evacuate, first of all, has, it's three words. It's the pointer to the vector on the heap. it's the length of the vector and it's the capacity of the vector. And this is so that if you try to push below the capacity, the length just gets incremented. If you try to push beyond the capacity, then the entire vector reallocates itself, copies over, and then changes.

[1:54:39] With a box U8, you can't do that. This will never grow or shrink. You can't push to it. It's just, think of it as a, it really is just a slice. You can turn a Vecuate into a Boxuate. And you can also go the other way around. But they're not the same, no. What's the difference between a dinfn and an fn?

[1:55:28] So basically, I can write a fnfoo that takes a dinfn. And I can write an fnbar that takes an fn. What's the difference between these? These are not the same. This has to be a function. It can't be a closure. And the reason for this is fn is really a function pointer.

[1:55:59] Like it's just a single pointer that has to be an address. This is a vtable. It's a trait object, which means that it both has a sort of the vtable you can think of here has a pointer to... calling the function, but it also has a data pointer, right? Because the the V, the structure of this is that it's a wide pointer, where one part is the V table, which has the pointer to call actually calling the function, but the other part is a data pointer. And crucially, the difference here is that if I have fn main, I can call foo with a closure.

[1:56:41] So I can do a function. This, but I can't do the same with bar. Why is it complaining? Oh. Right, so I can call foo with a closure because this captures x, right?

[1:57:16] So it's not just a function pointer, it's a function pointer and the data that the closure captures from its environment. That is, it needs to, when you call the closure, you also need to supply the address of x because it's needed by the body of the closure. and that's what's passed in the data part of the wide pointer. For bar, it requires an actual just function pointer, which means that you can't pass a closure because you wouldn't have anywhere to stick the data. When we use dinfn over implfn, yeah, so there's also bazf implfn.

[1:58:03] Um, and I can call Baz with a closure. What is it? What's it complaining about? I can call baz with a closure because remember, implfn is sort of sugar for a generic function over anything that is fn.

[1:58:34] So we actually get a concrete copy of baz for every type of closure that's passed in. And therefore, you can trivially pass in the data as well because it's monomorphized to each individual closure. The question then becomes, when do you use a dinfn, when do you use an implfn? The basic answer is... Implafen is more generally usable. Like you don't have to indirect behind a pointer, for example. But you end up generating a copy of Baz for each closure type you pass in, which might become quite a lot.

[1:59:12] And the other reason is because sometimes you want to take a trait object instead of making it generic because otherwise you have to propagate the generic type up. So imagine that I had a... struct wrapper, then internally I want it to contain a function pointer. If I have it hold, like I could write this, right? I could do this, but this means that anyone who wants to, any user of my library that wants to hold a wrapper would also themselves need to be generic over f or name the type of f.

[1:59:51] Whereas if this instead stored a box din fn, the now wrapper is no longer generic, so my callers don't have to think about and propagate that generic parameter. So sometimes it cleans up your interface and makes it just nicer to use. There's also the example of trait, making traits object safe. So if I have a trait x that has an fn foo, If I make this take an impl fn, then x is not object safe.

[2:00:28] I couldn't write a crocs. I guess let's have this take self. the trait x is not object safe because this is generic. implfn is equivalent to saying f is fn and this is f.

[2:01:01] And this cannot be made object safe like we talked about. But on the other hand, if I made this dinfn, It can be object safe because there is only one foo, right? So we don't have this problem of you need an infinite number of entries in the V table, there's only one foo and it itself takes a wide pointer, which then works for any type that can be a object safe. So there's not a clear cut answer here. Um, Nice.

[2:01:49] Okay, I think, I think that captures... everything I wanted to talk about. So the one thing that we didn't get around to talking about is coherence. I think coherence is different enough that we're not going to talk about it this stream and I might just do a separate stream on it, especially because we're on like the two hour mark. So I think this is a good time to stop.

[2:02:22] and then just do this separately. Are there any sort of questions towards the end about all the stuff we've talked about so far? Is the general difference between static dispatch and dynamic dispatch, the size trait, V tables, object safety, wide and fat pointers, does all of that roughly make sense now? Or is there anything more I can go through to sort of help crystallize it in your mind and make it clear why we have these, what they're for, what their limitations are? I'm happy to take some questions towards the end here.

[2:03:00] Could runtime trait detection be implemented in the future using a types of vtable? If I understand your question correctly, I don't think it can. So the idea is that can you take a trait object or can you take a wide pointer and figure out which traits it implements just by looking at its V table? I don't think you can. Part of the reason is because a different vtable gets generated for each trait object.

[2:03:37] So it's not like there's one vtable for str or for string, right? There are many vtables for string. There's one vtable for string for each din trait, right? Um, and so there's not just one, one V table that you could then look at to figure out what, what traits it implements. Um, like if you had like a find traits that took an S that was a din, like didn't trait, um, then the only things in the V table would be whatever methods are on the trait that you name here.

[2:04:24] You wouldn't get a V table of all possible methods on the provided type. So no, I don't think you can do dynamic detection of which traits something implements this way. Does calling a dinfn involve a double dereference, once for the Vtable pointer, once for the actual function pointer within, or does that get optimized away? So if I do call takes an F of Fn, and in here I do F.

[2:05:07] You know, that's a good question. I think it'll end up being a double D reference because you first have to go through... It's not quite a double D reference because this is a wide pointer, right? It's not, it's not a pointer to a tuple of a pointer and a V table, right? It it's really what gets passed in is a pointer to some T.

[2:05:39] You just don't know what the T is and a pointer to T's FN V table. That's really what's passed in here. And so this ends up calling like Vtable.call of t. And so there is a dereference here. Like, this is a pointer to the Vtable.

[2:06:12] So you do have to dereference the Vtable. I guess this is a better way to sort of type it out. So you do have to dereference the Vtable to get to the call. It's really, I guess, this, right? You have to dereference the V table to find the address of the call that you then call. So it does end up being two dereferences, but it's not quite pointer chasing either. It is true.

[2:06:58] Okay, so there is one thing that's a little bit funky, right? Which is if you have an X that takes an S of, let's say, din S ref str, then one thing you could do, and this was mentioned in chat, with the new pointer Vtable dynamic metadata RFC, you could imagine like, if s.Vtable is equal to string as din asrefster.Vtable, then like, s as reference f s dot data as reference to string dot i guess if this was a mute uh dot push right like maybe you could do some really weird ugly magic like this

[2:08:02] I would recommend just don't do it. But yeah, you could imagine you could compare V tables this way. I don't know if this is even a guarantee that the compiler will uphold that a type will always have only exactly one V table. And yeah, the compiler does do a decent amount of optimization here too. Like if you do a box din FN, I think it like might not do a heap allocation always if you like, if just like escape analysis and stuff. But in general, if you use generics, like if you use an actual generic type parameter or an impl block, sorry, an impl trait, In those cases, you will get better optimization just because the compiler gets full insight at compile time into what all the relevant types are and can co-optimize based on the actual concrete implementations.

[2:08:52] Whereas once you have indirection through dynamic dispatch, the compiler loses some of the information it would otherwise have and be able to optimize based on. Can you do a quick example of the sliceVec of DINs? Oh, yeah. Say hi's. So if you actually wanted to do like, I guess we had DIN hi, but let's make it DIN asref stir. Then you wanted like for H and S.

[2:09:27] Let's make it V. For S and V, S.asref. Um, so to actually get this to work, uh, what you end up with is you have to do this, um, to make the sized, right. Um, so that all of the elements of the array are the same size because the raise required that so that you can find the given index. Right. Um, and once you do that, um, the salt just works.

[2:09:59] And you could put a box or arc or whatever for the inner type too. Different compilation units can lead to different V tables. That sounds about right. So this is a little bit anecdotal, but when you compile Rust code, Rust might compile one crate using multiple independent threads to compile different subsets of the crate to sort of speed up compilation. But because you want those separate units to work in like entirely concurrently without too much synchronization, they might both encounter, let's say, a...

[2:10:37] string being used as a din-asref, they might both generate their own vtables because they don't want to coordinate about generating the vtables and therefore you have multiple vtables even for the same type for the same trait. So that's one example why that invariant might not hold. That's a good point. And yeah, there is also any, which I haven't talked about. I'm not going to actually demo it, but so there's the any trait. And any is super magical.

[2:11:09] It's not actually like any is just a trait that has a function that returns an identifier for a type. that is unique, guaranteed by the compiler. And so if you have something that's a trait object over any, you can use type ID on it because it gets added to the V table to get a unique... type identifier for that value and then you can use that to downcast from a din any to the concrete type because we know what the type identifier is i'm not going to go into any too much but but any uses a lot of the stuff that we've talked about so far to actually be able to go from a din a dim trait as long as that trait includes any into a reference to the actual underlying type.

[2:12:02] It's really cool and actually surprisingly simple now that you know what you know. So I recommend you give a read to the standard AnyModule documentation. It talks about why this is safe. Alright, I think we're going to end it there. 2 hours and 15, I'm pretty happy with that. We covered a lot. I hope that was useful. I hope you feel like you learned something and some of this might actually stick. I have made a little bit of progress on my coding live stream that I really want to happen.

[2:12:36] I'm hoping it'll happen sooner rather than later, but it has not escaped me. I'm still on the case. Thanks all for coming out and I will see you next time. So long farewell!

Vidleaf リーダーで開く

文字起こしを検索し、行を選択し、タイムスタンプ付きで引用をコピーし、翻訳します。

出典表示

Jon Gjengset氏による「Crust of Rust: Dispatch and Fat Pointers」(https://www.youtube.com/@jonhoo)、CC BY 4.0(https://creativecommons.org/licenses/by/4.0/)の下でライセンスされています。ソース動画:https://www.youtube.com/watch?v=xcygqF5LVmM。このページは、段落区切りとタイムスタンプを追加した動画のテキスト文字起こしです。制作者はVidleafと提携しておらず、Vidleafを推奨するものでもありません。VidleafはAIによる句読点の付加とAI生成の要約を追加しましたが、元の文言はこのページで引き続き参照できます。

あなたは制作者または権利者ですか? 訂正または削除を依頼する: copyright@vidleaf.app (これらのページについてをご覧ください)。

最終更新