Rust 的核心:派送、單態化與胖指標 — Jon Gjengset
本頁標題、字幕、摘要與閱讀筆記為已儲存的 AI 譯文,可能有誤。時間戳與來源一致,可展開查看原始字幕,並對照原影片核對。
Jon Gjengset 深入探討 Rust 中的靜態與動態派送,涵蓋泛型、單態化、虛擬函式表、特徵物件、自動特徵與 Sized 界限。
逐字稿來源:創作者上傳至 YouTube 的字幕。AI 標點由 Vidleaf 加入;原始措辭與時間戳錨點均保留。原始逐字稿可在下方取得。
AI 生成摘要
這段 Rust 串流涵蓋了一組半相關的主題——特徵、靜態與動態分派、Sized 特徵、寬指標或胖指標、虛擬表(vtable)以及連貫性——旨在說明它們如何相互配合,而不會過度深入任何單一細節,為了控制時間可能會跳過一些細節,深入探討可能留待後續。它解構了 Rust 聖經中關於泛型效能的章節,特別是單態化:在編譯期填入具體型別,將泛型程式碼轉換為特定程式碼,例如當一個泛型 strlen 接受任何實作 AsRef<str> 的型別,並以 &'static str 和 String 呼叫時,編譯器會產生兩份副本,或者當泛型 HashMap 針對使用的每個型別取得其結構體與方法的副本,並按需產生。這使得將 Rust 程式碼作為函式庫(例如動態連結函式庫)發布變得有些困難,因為需要原始碼才能為取用端的型別產生實例;優點包括透過內聯和最佳化可能產生更高效的程式碼,而缺點包括二進位檔較大、指令快取效率稍差,以及一些編譯器成本。靜態分派透過為 str 實作的自訂特徵來解釋,其中具體型別在編譯期已知,因此呼叫會變成對已知位置的組合語言呼叫;動態分派是當不希望有多份副本時的替代方案,例如一個裝有實作該特徵之各種東西的向量。演講接著解釋為何無法建立包含不同型別的向量、GUI 繪製範例、以 dyn 表示的 trait 物件、每個特徵界限隱含要求的 Sized 標記特徵、型別抹除、持有資料指標和虛擬表指標的胖指標、物件安全規則,以及為何 Clone 和 Extend 等特徵無法成為 trait 物件。後續段落涵蓋動態大小型別、trait 物件與分派:一個 DIN 特徵會變成一個 pointy 特徵,其元資料是 DIN 元資料,一個指向虛擬表的指標,該虛擬表持有型別大小、對齊、drop 和放置指標,以及方法指標;pointy 特徵同樣可以為 U8 切片實作,而不需要參考,並以 U 大小長度作為元資料。該功能仍屬新穎且實驗性,講者建議閱讀 RFC,其中包含一個 trait 別名 thin,適用於任何實作 pointy 且元資料為空的型別,提供用於內省指標元資料的方法,並且關鍵是允許在執行期即時建構虛擬表,正如標準函式庫已經為非同步中的 waker 所做的那樣。他對比了 fn、dyn fn 和 impl fn,指出對於 U8 切片的參考如何儲存其長度尚不確定,並解釋只有結構體的最後一個欄位可以具有動態大小型別。聽眾要求一個裝有 dyn 的切片 Vec,引出了 trait 物件、虛擬表和 Any 特徵:陣列元素必須被做成相同大小,而不同的編譯單元可能會為相同型別和特徵產生不同的虛擬表。Any 被描述為一個特徵,其函式回傳編譯器唯一的型別識別碼,並被加入虛擬表以允許向下轉型。會議在大約 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 泛型的函式,其中 S 實作 AsRef<str>,兩者都是接受任何可轉換為 str 參考之型別的泛型函式。
- [4:36] 函式 foo 以 "hello world"(一個 &'static str)以及 String::from("hello world")(一個 String)呼叫 strlen,顯示這兩次呼叫傳入不同的型別。
- [5:30] String 實作 AsRef<str>,因為對 String 的參考可以輕易取得對 str 的參考,這是因為 String 的內部表示就是 str。
泛型呼叫的單態化
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] 單型化仍會導致最終二進位檔中有更多程式碼,這點依然成立。
指令快取效率與編譯成本
Rust 二進位檔大小、單型化與泛型
Rust 執行檔較大的原因
- [12:38] 單態化是執行檔較大的部分原因,而且可能會有更多標準函式庫程式碼被編譯進去。
- [12:48] 另一個重要因素是 Rust 經常會建入除錯符號,因此嘗試對執行檔進行 strip 可能值得一試。
泛型函式的單態化與內聯
- [13:07] 單態化有幫助,因為像 bool_then 這樣的泛型函式可以產生一份副本,並將傳入的閉包程式碼直接內聯進去。
- [14:18] 內聯並非保證:因為函式已針對特定型別單態化,編譯器知道該型別,因此可以視情況選擇內聯並最佳化。
標準函式庫的使用與程式碼重複的成本
參照與動態連結的限制
Rust 中的靜態派發與單態化
定義自訂的 Hello trait
- [16:40] 講者定義了一個自訂 trait,稱為 Hello(或挪威語的 hi),它只有一個方法,不回傳任何值,只是用挪威語說 hello。
- [17:10] 這個 trait 為 str 實作,該方法使用 self 印出一行文字。
對具體 str 參照的方法解析
- [17:46] 當為對 str 參照的呼叫產生程式碼時,編譯器會判定型別,並檢查該參照型別上有哪些方法可用。
- [18:06] 它在參照型別上找不到名為 hi 的方法,接著查看作用域中的 trait,找到為接收者型別實作的 hi 方法,於是呼叫該方法。
泛型函式與單態化
- [18:21] 在接收實作 hi 之型別的泛型版本中,編譯器必須在不知道 H 型別的情況下呼叫該方法。
- [18:47] 單態化會產生具體版本,例如將 H 綁定為 str 的 bar_str,因此具體型別是已知的。
編譯期靜態派發
動態派發作為單態化的替代方案
靜態派發與 impl Trait 語法糖
動機:避免產生多份副本
單一具體型別的切片
- [21:29] 如果所有元素都是相同型別,走訪向量並呼叫 `h.high` 沒有問題。
- [21:51] 一個接受實作 High 之項目切片的函式 `bar` 可以運作,且以單一具體型別呼叫時能順利編譯。
- [22:27] 將每個元素轉成字串也沒問題,不過講者指出他們尚未為 string 實作這個。
異質集合的需求
動態派發與特徵物件
將不同的具體型別視為同一型別
- [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 的意義和它與動態派送及特徵物件的關聯。
型別抹除作為預期目標
為何 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 可能大到一 GB,所以切片沒有單一的元素大小。
- [32:28] 切片是一塊連續記憶體,其中每個區塊大小相同,所以若元素大小未知,就無法保證元素大小相同。
- [32:52] 若元素大小不同,就無法產生第四個元素的指標運算(起點加上元素大小的三倍),這就是切片與陣列的元素必須是定大小型別的原因。
修正未定大小集合的問題
Rust 的 Sized Trait 與未定大小型別
未定大小引數的編譯器錯誤
- [33:57] 編譯這個範例會產生錯誤:型別 din sRF str 的值大小無法在編譯時期得知,而且 din as ref 並未實作 Sized。
- [34:17] 編譯器要求函式引數具有靜態已知的大小,而借用型別的大小則總是已知。
- [34:26] 編譯器必須知道引數型別的大小才能產生函式呼叫的程式碼,這使得定大小型別成為基本要求。
Sized 的自動實作
- [34:59] 任何能夠實作 Sized 的型別都會自動實作 Sized,所以沒有欄位的結構體,或持有 String 或 bool 的結構體,都是定大小的。
- [35:27] 泛型結構體 foo<T> 仍然是定大小的,因為每個 trait 界限都隱含著 T: Sized 的要求,所以所有欄位都是定大小的。
- [35:50] 你永遠不會自己實作 Sized;它只會被當作自動 trait 使用。
為何編譯器需要已知的大小
- [36:09] 問題不在於堆疊大小,也不在於某個值是否可能放不進堆疊。
- [36:18] 在機器碼或組譯層級,呼叫函式需要知道要為其堆疊變數、引數與回傳值配置多少空間。
- [36:49] 雖然有取巧的方法可以做到,但編譯器必須知道這些東西的大小才能產生有效率的程式碼。
未定大小型別的範例
解決 Sterling 2 的單態化問題
針對 Sterling 2 提出的非單態化方法
為無大小的特徵型別加上間接層
透過指標讓無大小型別變得有大小
- [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] 建立 box 時必須給它一個具體型別的東西,而此時它會為該型別配置堆積空間。
- [42:57] box 的大小仍然是已知的,因為它就只是一個指標,即使它所指向的東西可能有任意大小。
- [43:13] 實際傳入函式的引數確實有大小,因此可以產生相關的程式碼。
Box 與參照的比較
Rust 中的 TraitObject 與型別抹除
TraitObject 的定義
- [46:17] 所建構出來的東西稱為 TraitObject,這種物件唯一的特性就是它代表某個 trait。
- [46:28] TraitObject 只會以某個底層 trait 的形式運作,不論外層包裝的型別是什麼。
- [46:44] Box 是一種指標型別。
轉換回具體型別
- [46:49] 將 trait 物件轉換回其原始具體型別通常是不可能的,不過技術上有時可以透過 unsafe transmute 或 any trait 做到。
- [47:03] 將值轉換成 trait 物件本質上就是型別抹除:關於它原本是什麼型別的知識都被抹除了。
- [47:26] 一般應忽略 unsafe 與 any trait 的魔法。
只剩下 trait 的方法可用
動態派送與 vtable 機制
泛型呼叫的編譯期程式碼產生
- [48:09] 當編譯器為函式產生機器碼時,最終必須產生可轉換成可執行機器碼的組譯碼。
- [49:29] 在一般情況下,編譯器會為每個具體型別取得一份程式碼副本,因此呼叫會變成直接跳躍到二進位檔中已知的記憶體位置。
- [50:05] 對於具體實作,編譯器在編譯期就能靜態得知要前往何處,使程式碼產生變得輕而易舉。
特徵物件與未知的具體型別
- [48:51] 像 sayHi 這樣的函式會接收 Hi 特徵的特徵物件,而這實際上只是一個指標,因此編譯器並不知道 S 是什麼型別。
- [50:14] 在動態情況下,編譯器不知道該值是 str 還是 String,因此無法決定要產生哪個位址。
虛擬派送表
- [50:29] 這種情況正是動態派送與 v table(即虛擬派送表)發揮作用之處。
特徵物件與動態大小型別
特徵物件指標中的額外型別資訊
- [50:38] 建構特徵物件意味著該參考或 box 不只一個指標寬;它會攜帶關於所指型別的額外資訊。
Rust 參考文件關於動態大小型別的說明
- [51:24] Rust 參考文件指出,大多數型別具有在編譯期已知的固定大小,並實作 Sized 特徵。
- [51:33] 大小僅在執行期才得知的型別稱為動態大小型別,非正式地也稱為無大小型別。
- [51:40] 切片與特徵物件是動態大小型別的兩個例子。
執行期型別判定範例
- [51:45] 大小僅在執行期才得知,因為在編譯期並不知道會使用哪個具體型別。
- [51:58] 在一個由使用者讀取的值決定 say_hi 接收數字或字串的範例中,實際型別僅由不可預測的輸入在執行期決定。
動態大小型別的指標大小
- [52:59] 指向動態大小型別的指標型別本身有大小,但其大小是指向有大小型別之指標的兩倍。
Rust 中的特徵物件與 Vtable
特徵物件參考的結構
V 表包含的內容
- [53:52] V 表(或稱虛擬派送表)是一種資料結構,儲存指向該型別之特徵各方法的指標。
- [54:10] 對 dyn Hi 而言,V 表可以想成是一個 Hi V 表結構體,其中有一個成員 hi,它是指向 Fn 的指標,該 Fn 接受指向任意 T 的指標。
- [54:47] 每個被轉換成特徵物件的具體型別都會建構出不同的 V 表。
在轉換過程中建構 V 表
- [54:57] 將 str 轉換成 dyn Hi 會得到一個指向 str 的指標,以及一個 Hi Vtable,其 hi 為 str as hi。
- [55:38] 在轉換過程中,編譯器會建構 Vtable 並將其位址儲存在參照內。
- [55:59] 每個被轉換成 TraitObject 的型別都有一個這樣的 Vtable。
產生的派送程式碼與各型別的 Vtable
Rust Vtable 與特徵物件佈局
Vtable 建構與胖指標
- [57:45] Vtable 是在編譯期靜態建構,而非動態配置。
- [58:01] 特徵物件是胖指標或寬指標,因為它包含兩個指標,而非一個。
- [58:16] 第二個指標通常是靜態已知的,因為它由特徵物件最初的建構方式決定,不過技術上仍可即時手動建構 vtable。
特徵物件中的字串切片表示法
Vtable 內容與除錯
Vtable 身分與去重
- [1:00:12] 每次建立實例時並不會建構新的 vtable;vtable 通常是為該型別靜態建構的。
- [1:00:32] 相同的 vtable 不會被去重,而且為兩個不同型別實作同一個 trait 保證會是相異的,即使它們包含相同的程式碼也一樣,因此它們的位址不同。
Box 與 trait 物件的指標寬度
含多個 trait 的 trait 物件與 vtable 限制
為何合併兩個 trait 會失敗
- [1:04:12] 若要讓合併 Hi 與 AsRef 的 trait 物件運作,編譯器必須知道 hi 方法與 asref 方法各自在哪裡,但這些方法位於兩個不同的 vtable 中。
- [1:04:29] 這需要的不是兩倍寬的指標,而是三倍寬的指標:一個指向資料的指標、一個指向 Hi 的 vtable 的指標,以及一個指向 AsRef 的 vtable 的指標。
- [1:04:44] 這樣的佈局並非本質上不可能,但每增加一個 trait 就會讓參考的大小持續增長,這大概不是原本的用意。
編譯器產生的合併 vtable 與 supertrait 變通做法
- [1:04:59] 理論上編譯器可以為這個組合產生一個 vtable 並傳入,但 Rust 編譯器目前不會這麼做,而講者也不知道有任何提案要這麼做。
- [1:05:11] 一個變通做法是宣告一個像 HiAsRef 這樣的 trait,要求型別同時是 Hi 與 AsRefStr,且本身沒有方法,藉此得到一個包含兩個 trait 方法的單一較大 vtable。
- [1:05:52] 這項功能之所以尚未進入 Rust 本身,部分原因是你可以自行選擇啟用,而沒有自動把加號變成更大的 vtable,是在向開發者示意這可能不是他們的本意。
多個 trait 的編譯器錯誤與建議
- [1:06:45] 撰寫 Hi + AsRefStr 會產生錯誤,指出在 trait 物件中只有 auto trait 可以作為額外的 trait,因為 Hi 與 AsRefStr 都不是 auto trait。
- [1:07:14] 編譯器建議建立一個新特徵,將這些全部作為父特徵,並在此處改用該特徵,同時指出像 Send 和 Sync 這類自動特徵沒有問題。
標記特徵與無方法的額外特徵
特徵物件與關聯型別
關聯型別導致特徵物件編譯失敗
- [1:08:51] 在特徵 high 中加入名為 name 的關聯型別,即使未使用,也會導致程式碼無法編譯。
- [1:09:28] 編譯器回報,在取用 dyn high 的地方必須指定特徵 high 中關聯型別 name 的值。
- [1:09:39] 你無法接受任何 high 而不論其關聯型別,因為該型別資訊無法被捕捉到虛擬表中。
指定關聯型別以恢復編譯
特徵物件的安全性與將方法排除於虛擬表之外
為何沒有 self 的關聯函式會破壞物件安全性
- [1:11:20] 編譯器回報該特徵無法被製成物件,意即它不具物件安全性,無法成為特徵物件。
- [1:11:34] 特徵要具備物件安全性,必須允許建立虛擬表,以便動態解析呼叫。
- [1:11:44] 錯誤訊息明確指出該特徵無法被製成物件,因為關聯函式 weird 沒有 self 參數。
- [1:12:17] 無法呼叫 s.weird,因為 weird 不接受 self 或指標,且沒有有效的實例可供指向。
- [1:12:36] 以 Hi::weird 呼叫會有歧義,因為沒有任何東西指定要使用哪個實作,即使存在預設實作也一樣。
- [1:13:14] 該方法無法放入虛擬表,因為沒有 self,所以它不與任何型別的任何實例相關聯。
以 where Self: Sized 將方法排除於虛擬表之外
- [1:14:21] 在 weird 加上 where Self: Sized 約束,會要求實作型別必須是 Sized,而像 dyn Hi 這類特徵除非放在指標後面,否則不是 Sized。
- [1:14:43] 這等於讓該函式退出 vtable,關鍵是使它無法透過特徵物件呼叫。
- [1:15:06] 加上這個約束後程式碼就能編譯,而且仍可建立特徵物件並呼叫 Hi。
- [1:15:30] 此時在特徵物件上呼叫 weird 會失敗,因為該方法有 Sized 的要求。
- [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] 因為它是 box,所以需要雙重引用,而這沒問題,因為 boxed 型別不是動態大小的;包在指標後面就讓它有大小,因此 trait 上的 `Self: Sized` 不會阻止這件事。
- [1:20:46] 如果問題指的是 `str` 或 `u8` 這類型別,不行,你做不到:當你有 `where Self: Sized` 時,Self 必須是有大小的。
vtable 中的型別抹除與關聯型別
標準函式庫中的 fromIterator 與 collect
fromIterator trait 與 collect
Rust FromIterator 與 Extend trait 的機制
FromIterator trait 的型別參數
- [1:21:38] 把迭代器收集成 Vec 之所以能用,是因為 Vec 實作了 FromIterator。
- [1:21:49] FromIterator 的關聯型別 A 是迭代器項目的型別,因此會產生該項目型別的 Vec。
- [1:22:00] 這個 trait 的泛型參數 T 是迭代器本身的型別,例如 HashMap 迭代器的型別。
- [1:22:10] Vec<T> 可以從任何項目為 T 的迭代器建構,無論具體的迭代器型別是什麼。
- [1:22:20] 講者指出這個參數或許應該命名為 I 代表 iter,但認為這不重要。
FromIterator 的 trait 物件問題
- [1:22:43] 使用 FromIterator 會對 trait 物件造成問題。
- [1:23:35] 一個接受 bool 的 FromIterator 並回傳 Vec 的函式,看起來應該沒問題。
- [1:23:45] FromIterator 是個不好的例子,因為它不接收 self,所以無論如何都要求 self 必須是 sized。
以 Extend 作為更好的例子
為何 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 會失敗
物件安全性與 Clone 特徵
物件安全特徵的要求
為何 Clone 無法成為特徵物件
- [1:31:38] 使用 dyn Clone 時,你只能做該特徵允許的事,而 Clone 只讓你進行複製。
- [1:31:47] 編譯器回報特徵 Clone 無法被製成物件。
- [1:31:58] Clone 有一個 fn clone,它接收 self 並回傳 self。
未定大小回傳型別的問題
- [1:32:03] 對於 let x = v.clone(),x 的大小並不明確,因為 dyn Clone 只是任何可複製的型別。
- [1:32:19] Clone 應該回傳 self,而不是對 dyn Clone 的參照。
- [1:32:26] 由於具體型別已被抹除,self 會是 dyn Clone,而它是未定大小的。
- [1:32:46] 函式的回傳型別必須是定大小的才能產生程式碼,因此這無法運作。
- [1:32:51] 因此,特徵若要具備物件安全性,就不能有回傳 self 的方法,這就是為何無法使用 Clone。
混用物件安全與非物件安全的方法
透過 where Self: Sized 讓 Iterator 特徵具備物件安全性
Iterator 的泛型方法與物件安全性
- [1:33:23] Iterator 特徵有關聯型別 Item 與具物件安全性的方法 next,但也有泛型方法,例如 chain、enumerate、by_ref 與 collect,其中 collect 依賴 FromIterator 且不具物件安全性。
- [1:34:01] 儘管如此,Iterator 仍是物件安全的:在 dyn Iterator<Item = bool> 上,無法對該特徵物件呼叫 collect,但可以用可變接收者呼叫 next。
where Self: Sized 會將方法從 vtable 中排除
- [1:35:03] 像 count 和 last 這類會消耗 self 的方法,都帶有 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,所以無法透過 trait 物件呼叫 last。
關於 trait 物件的秘密
- [1:39:55] 講者指出,關於 trait 物件至少還有一件事尚未涵蓋:trait 物件的一點小秘密。
Drop 與 trait 物件的 vtable
Drop 作為物件安全的 trait
- [1:40:16] Drop 其實是物件安全的,儘管一個只能被 drop 的物件似乎沒什麼意思。
- [1:40:26] 這在垃圾回收等情境下很有用,物件不會立即被 drop,而是存放在連結串列中並定期回收。
- [1:40:43] 將許多可能不同的事物存放在同一型別中需要 TraitObjects,因此 Crossbeam 將它們存放在 drops 中,技術上是裝箱在 drops 中,效果相同。
透過 vtable 進行 Drop
- [1:40:59] 當 v 離開作用域時,會透過 vtable 呼叫 dropDrop。
- [1:41:34] 當裝箱的 s 離開作用域時,存在一個堆積配置,可能在 s 於函式返回時被 drop 之前透過 s.asref 使用。
- [1:41:56] drop 一個 box 需要釋放記憶體,但一個唯一方法是 asref 的 trait 物件仍需要一種方式來做到這一點。
- [1:42:06] 每個 vtable 都包含 drop,因此任何 TraitObject 的 vtable 都包含指向具體型別 drop 函式的指標,這是必要的。
vtable 中的大小與對齊
Rust 中的未定大小型別與寬指標
trait 物件之外的未定大小型別
- [1:43:04] 除了 trait 物件之外,其他型別也是未定大小的,例如 [u8] 和 str。
- [1:43:20] 當 trait 物件放在參照或指標後方時,它會變成由資料指標與 vtable 指標組成的元組。
- [1:43:34] 指標後方的切片會變成寬指標,內含一個資料指標與一個存放切片長度的 usize。
- [1:43:50] 同樣地,指標後方的 str 會表示為一個資料指標加上一個 usize 長度。
未定大小引數與回傳值的編譯器錯誤
- [1:43:57] 以傳值方式接收 [u8] 的函式會被拒絕,因為型別 [u8] 的值大小未知,畢竟 [u8] 是長度任意的 u8 清單。
- [1:44:21] 直接回傳裸 [u8] 同樣會失敗,因為函式的回傳型別必須具有靜態已知的大小。
以參照與 Box 遮蔽未定大小性
Rust 的未定大小型別與胖指標中繼資料
動態大小型別帶來的編譯器挑戰
- [1:46:04] 動態大小型別在編譯器中有些特殊,因為它必須知道某個指標是否為寬指標。
- [1:46:14] 自行處理未定大小型別相當困難,不過為未定大小型別實作類似 box 的東西是可行的。
- [1:46:27] 一旦涉及型別轉換與允許 trait 物件,就會變得麻煩。
RFC 2580 與 Pointy trait
- [1:46:33] 最近通過的 RFC 編號 2580,新增了一套用於操作胖指標中繼資料的泛型 API。
- [1:46:48] 這套 API 讓你能指定胖指標第二部分的型別。
- [1:46:58] DIN trait 會變成 pointy trait,其中繼資料為 DIN 中繼資料,也就是指向 vtable 的指標,該 vtable 存放型別大小、對齊、drop 與 place 指標,以及方法指標。
- [1:47:28] pointy trait 同樣可以為不帶參照的 U8 切片實作,並以 U 大小的長度作為中繼資料。
實驗性狀態與 Thin trait 別名
- [1:47:44] 這項功能仍很新且處於實驗階段,講者建議閱讀該 RFC。
- [1:47:52] 該 RFC 包含一個特質別名 thin,適用於任何實作 pointy 且中介資料為空的型別,也就是 thin 指標而非 fat 指標。
中介資料內省與執行期虛擬表
以原始 Waker 作為手動虛擬表範例
Rust 的 DST、切片,以及 Box 與 Vec 的比較
切片中介資料與自訂動態大小型別
- [1:50:38] 講者不確定對 u8 切片的參照是儲存起始與結束指標還是長度,並指出兩者基本上等價。
- [1:51:01] 所引用的 RFC 棄用了 Nightly 中存在的特質物件與 raw parts 項目中的 thin 中介資料,因為它是替代方案。
- [1:51:29] 講者希望該 RFC 會說明切片的關聯中介資料型別,但並未看到,並認為它就只是長度。
- [1:51:46] 你多少可以製作自己的動態大小型別:一個以 u8 切片作為最後欄位的結構體會變成無大小。
- [1:52:14] 只有結構體的最後欄位可以具有動態大小型別,因為若前面的型別具有任意大小,中間欄位的位移就無法計算。
- [1:53:07] 若無大小欄位在最後,較早欄位的位移是靜態已知的,且只需最後欄位的長度即可使該型別有大小。
- [1:53:18] 對此類結構體的參照藉由將指標與最後欄位的長度一起儲存而具有大小。
Box<[u8]> 與 Vec<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] 若包裝結構體儲存的是 box din fn 而非對 f 泛型,則該包裝就不再是泛型,因此呼叫端不必具名或傳播泛型參數,這能讓介面更簡潔。
帶有 fn 參數之特徵的物件安全性
一致性延後處理;關於分派、vtable 與特徵偵測的 Q&A
將一致性延後到另一個串流處理
回顧派送與 trait 物件概念
- [2:02:29] 講者詢問,靜態派送與動態派送之間的一般差異、size trait、vtable、物件安全性,以及寬指標與胖指標,大致上是否說得通。
- [2:02:45] 講者表示願意再講解更多內容,以釐清這些東西為何存在、用途是什麼,以及有哪些限制。
為何無法透過 vtable 在執行期偵測 trait
dyn Fn 呼叫中的雙重解參考
dyn Fn 的寬指標配置
- [2:05:23] 這並不算完全的雙重解參考,因為傳入的引數是寬指標,而不是指向「指標與 vtable 組成之元組」的指標。
- [2:05:33] 傳入的是一個指向某個型別未知之 T 的指標,再加上一個指向 T 的 Fn vtable 的指標。
解參考 vtable 以取得 call
動態派送、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 trait 通常能獲得更好的最佳化,因為編譯器在編譯期能完整掌握相關型別,並可依據具體實作進行共同最佳化。
- [2:08:52] 透過動態分派進行間接呼叫時,編譯器會失去一些原本可用於最佳化的資訊。
請求的切片範例
- [2:09:07] 一位聽眾要求提供一個 dyn 的切片 Vec 的簡短範例。
Rust 特徵物件、vtable 與 Any 特徵
讓 dyn AsRef 陣列搭配定長元素運作
- [2:09:15] 若要將類似 dyn AsRef<str> 的東西用於 H 與 S,你必須讓陣列元素大小相同,因為陣列需要如此才能找到指定的索引。
- [2:09:56] 一旦元素大小相同,這個做法就能運作,你也可以為內部型別放入 Box 或 Arc 或類似的東西。
為何 vtable 在不同編譯單元間可能不同
- [2:10:08] 不同的編譯單元可能導致不同的 vtable。
- [2:10:12] 根據經驗,Rust 可能會使用多個獨立的執行緒來編譯同一個 crate 的不同子集,以加快編譯速度。
- [2:10:25] 由於這些獨立的單元在幾乎沒有同步的情況下並行運作,它們可能都會遇到同一個被用作 dyn AsRef 的字串,並各自產生自己的 vtable,而非進行協調。
- [2:10:40] 這可能導致即使型別與特徵都相同,仍產生多個 vtable,這正是該不變量可能不成立的一個例子。
Any 特徵如何實現向下轉型
- [2:10:57] Any 特徵被形容為極其神奇,但它其實只是一個帶有函式的特徵,該函式回傳一個由編譯器保證唯一的型別識別碼。
- [2:11:19] 對於以 Any 為基礎的特徵物件,你可以在其上使用型別 ID,因為它會被加入 vtable,從而取得該值的唯一型別識別碼。
- [2:11:28] 該識別碼讓你能從 dyn Any 向下轉型為具體型別,因為你知道型別識別碼是什麼。
- [2:11:46] Any 運用了大量先前討論過的機制,從 dyn 特徵(只要該特徵包含 Any)轉換為指向實際底層型別的參照。
關於 Any 安全性的推薦閱讀
串流收尾與未來的程式設計計畫
工作階段結論與長度
規劃中的程式設計直播
結尾致謝
- [2:12:44] 他感謝大家前來參與,並說下次再見。
前 3 段雙語對照預覽 · 免消耗額度
以下展示前 3 段已儲存繁體中文譯文與英文原版字幕的逐段對照(零額度消耗):
各位好,歡迎回到又一集的 Crust of Rust。這一集,我希望我沒有攬下太多內容,以免無法在一個半到兩個小時內講完。我想等你們之後看這份錄影時,就會知道我是否成功了。所以這一集,我想涵蓋的是……一大塊圍繞 trait、動態與靜態分派、size trait,也就是寬指標或胖指標的半相關主題。
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.
還有一些關於 V table、連貫性(coherence)之類的東西,它們都有這種動態與靜態的做法。它們全都彼此牽連,有些牽連得比其他更緊密。而每一個我都收到很多問題。我想我應該就做一集直播,把這些東西全都怎麼運作、怎麼彼此契合講一遍。我希望我們……最後不會在任何一個主題上鑽得太深。我想我會試著以大致可用的細節涵蓋大部分內容。
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.
然後我們之後也許會在某集直播中對其中一個做深入探討。但為了盡量控制時間,你們可能會發現我跳過了一些細節,希望這樣沒問題。所以這次我其實想從 The Rust Book 開始。The Rust Book 有一章講泛型型別、trait 和生命週期。裡面有一個小節講使用泛型的程式碼效能。這一節,如果你讀過這本書——如果你還沒讀過,我強烈建議你讀——可能會讓你覺得,你可能讀到時會想,這聽起來像魔法一樣。
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。這一集,我希望我沒有攬下太多內容,以免無法在一個半到兩個小時內講完。我想等你們之後看這份錄影時,就會知道我是否成功了。所以這一集,我想涵蓋的是……一大塊圍繞 trait、動態與靜態分派、size trait,也就是寬指標或胖指標的半相關主題。
[0:44] 還有一些關於 V table、連貫性(coherence)之類的東西,它們都有這種動態與靜態的做法。它們全都彼此牽連,有些牽連得比其他更緊密。而每一個我都收到很多問題。我想我應該就做一集直播,把這些東西全都怎麼運作、怎麼彼此契合講一遍。我希望我們……最後不會在任何一個主題上鑽得太深。我想我會試著以大致可用的細節涵蓋大部分內容。
[1:18] 然後我們之後也許會在某集直播中對其中一個做深入探討。但為了盡量控制時間,你們可能會發現我跳過了一些細節,希望這樣沒問題。所以這次我其實想從 The Rust Book 開始。The Rust Book 有一章講泛型型別、trait 和生命週期。裡面有一個小節講使用泛型的程式碼效能。這一節,如果你讀過這本書——如果你還沒讀過,我強烈建議你讀——可能會讓你覺得,你可能讀到時會想,這聽起來像魔法一樣。
[1:59] 而某種意義上,這個串流要做的,就是試著拆解那個魔法,看看裡面到底有什麼。特別是,它談到了單型化這個概念。而單型化,正如書上所說,是透過填入編譯時所使用的具體型別,把泛型程式碼轉變成特定程式碼的過程。但這有點抽象。所以我們試著舉一個稍微具體一點的例子,再從那裡往下推。我們就用 new lib 吧。
[2:34] 我們要把這個命名為。嗯,命名很難。叫什麼都無所謂,但這反而更難,因為沒有任何限制。我們就用挪威文寫的 example 吧。好,把這個測試刪掉。
[3:06] 我們不需要測試。所以假設你有一個函式 greater。它對 T 泛型。其實,我們再簡單一點。假設我們要有一個函式 strlen。它會接收任何實作了 ASRF str 的東西。然後回傳一個 use size。所以我們就做 as ref len。
[3:39] 非常簡單的函式。讓我把它弄大一點。所以這是個泛型函式。你同樣也可以把它寫成 s 是 s to use size,其中 s 實作了 s ref stir。這兩個是等價的。s ref len。我想我們會把這些設成 pub,讓編譯器不再抱怨。
[4:12] 所以這兩個是等價的。它們不完全等價,但做的是同一件事。而且兩者都是泛型函式。它們可以接收任何能轉變成 star 參考的型別,這就是這裡所說的,也和這個 trait bound 所做的一樣。而會發生的事是,如果我們寫任何函式,比如說 foo,它呼叫 strlen 傳入,比如說,hello world。然後它也呼叫 strlen 傳入 string from hello world。
[4:53] 用挪威文。那是挑選範例的好用捷徑。所以,為了看出為什麼這些不同,這裡傳入的是 static str 型別。這裡傳入的是 string 型別。哇。對吧?所以這就是我們進入重點的地方:這個函式是泛型的。它不只接受字串參考。
[5:25] 它接受任何能轉變成字串參考的型別。所以,比如說 string 就實作了 as ref str。因為如果你有一個字串的參考,你就能輕易取得一個 str 的參考。因為字串的內部表示就是一個 str。對吧?所以在這裡我們馬上就看到泛型為什麼有用。這是因為它讓你以更有彈性或更符合人體工學的方式呼叫某個函式。而在背後,會發生的事,也就是 Rust 書在談到單型化時所說的,就是編譯器實際上會產生這個函式的兩份副本。
[6:08] 每種類型各一個。所以在編譯時期,我們實際上最終會得到像是 SterlingRefStir 這樣的東西,它接收一個 stir 並呼叫 studLen。而我們最終會得到 SterlingString,它接收一個字串並做同樣的事。所以這個泛型定義會被編譯器轉換成這些多個非泛型的實作。
[6:48] 這就是單型化的過程。而這正是 Rust 中泛型運作的關鍵。這個過程不只發生在函式上,類型也會發生。所以想像你有一個對鍵和值泛型的雜湊映射。你實際上會得到整個結構體及其所有方法的完整副本,每個使用它的類型各一份。注意它不會為我們沒有用到的類型產生副本。
[7:18] 這不像為每個可能的類型都產生。而是按需為任何類型產生,但按需是在編譯時期決定的。如果你看到程式碼需要這個函式用於某個給定類型,就在那個時間點產生它。類型也是一樣。像是雜湊映射,特定的一個雜湊映射類型實例只會在那個類型組合實際出現在程式碼某處時才會被產生。這實際上也是為什麼要讓 Rust 編譯 Rust 程式碼,然後把二進位檔發給別人當作函式庫使用會有點困難的原因之一。
[7:58] 因為想像如果你在 Rust 函式庫中有這個東西,而你想以二進位形式散布,想想動態連結函式庫之類的,這實際上相當複雜,因為契約是 Rust 應該為每個類型產生這個函式的不同副本,但它可能在消費者端以一個未定義在原始函式庫中來源函式所在位置的類型來實例化。因此,你需要原始碼才能產生所有那些實例。
[8:31] 而單型化之所以很棒,是因為你最終會產生可能更有效率的程式碼,對吧?Sterling 在這裡是個不太好的例子,但讓我們想像我們有稍微複雜一點的東西。實際上,一個好例子是 HashMap。我不會在這裡寫出 HashMap 的完整定義。但你最終會得到 HashMap,因為你會為每個使用的具體類型得到該類型的副本。想像其中一個 HashMap 實例的鍵是...
[9:06] 一個字串,而另一個實例的鍵是數字,那麼當編譯器為 HashMap 的每個方法產生程式碼時,它實際上會為每種鍵型別內聯雜湊函式的定義。因此,使用字串的那個 HashMap 程式碼版本,會直接把雜湊字串的程式碼放進 HashMap 的程式碼中,並且能根據該型別是字串這個事實來最佳化那段程式碼。
[9:40] 同樣地,對於數字這類東西,它可能可以完全跳過雜湊,因為它一旦把所有泛型單態化之後,就會發現雜湊其實就是數字的值。這可能實際上並不成立,但你可以體會到那個意思:編譯器能看到所使用之特定型別的具體展開程式碼,這讓它能最佳化得更好。在我們進入這個主題更複雜的部分之前,這些都說得通嗎?泛型的一般概念,以及為什麼單態化很好,這些都說得通嗎?
[10:28] 所以缺點,正如聊天室裡有人觀察到的,沒錯,對於單態化來說,其中一個缺點就是你的二進位檔會變大,因為你需要為每個使用到的型別產生一份該型別或函式的副本。它並沒有像單純乘以型別數量那麼糟。原因之一是,以 HashMap 為例,對於任何給定的型別組合,你可能只會用到一部分的方法。它不會產生像是……如果你曾經有一個以字串為鍵型別的 HashMap,它並不會產生整個 HashMap,也就是字串鍵型別的所有 HashMap 方法。
[11:08] 它只會產生你實際呼叫到的方法。所以這稍微攤平了一些成本。但確實,它會導致最終二進位檔中有更多程式碼。而這帶來的一個副作用是,你的程式碼在效率上可能會稍微差一點,因為現在不再是只有一個叫做 Sterlin 的函式,也就是一段組合語言、實際上是機器碼的序列,讓電腦可以跳轉過去。
[11:40] 然後它可以把那些機器碼行保留在快取中,讓它下次執行時更有效率。但實際上你會得到的是兩個不同的函式,有些程式碼會跳到其中一個,有些會跳到另一個,而它們必須分別快取,因為它們是記憶體中不同的區域,所以你的指令快取效率實際上會稍微變差,這是一個缺點。這在某種意義上也稍微昂貴,因為編譯器確實需要產生這些副本,但通常這不算太大的成本,除非你用非常大量的型別來實例化。
[12:22] 嗯,這是 Rust 二進位檔比 C 二進位檔大的主要原因之一嗎?這稍微有點不同。Rust 二進位檔會靜態編譯更多東西,這可能是部分原因。一部分是單型化。一部分是——我忘了確切細節——但我認為標準函式庫有更多東西會被編譯進去。另一個很大的原因是 Rust 經常會建入除錯符號。
[12:54] 如果你沒有從二進位檔中移除它們,最後得到的二進位檔實際機器碼很少,但除錯符號很多,所以你或許可以試著直接移除二進位檔中的符號。編譯器會嘗試內聯產生的函式嗎?會,這就是單型化非常棒的其中一個原因,因為它不只是內聯它是 string 還是 str,而是如果你有一個比如 PubFn,像是……一個 bool then,它接受一個布林值,並接受一個 f,也就是一個函式,然後回傳一個 option t。
[13:42] 然後假設實作大概是:如果 b,就 some f,否則……。而這個函式其實才剛進入標準函式庫,不過是作為 bool 上的方法。所以在這裡,如果你曾用某個特定的……閉包或函式來執行這個函式,它實際上會產生一份 bool then 的副本,並把你傳入的閉包程式碼直接內聯到這個函式中。因此它就能據此進行最佳化。
[14:14] 所以是的,它最後確實會內聯。內聯在這裡是錯誤的用詞。它有內聯並據此最佳化的選項。它不一定非得這麼做。只是因為它會被單型化成特定型別,它確切知道那個型別是什麼,所以它可以選擇要不要內聯,這是很重要的區別。檔案較大的主因是標準函式庫。
[14:44] 這不完全正確,因為只有你實際使用到的標準函式庫部分才會被放進你的執行檔中。不過,如果你大量使用標準函式庫中的泛型,那確實會讓體積變大。方法重複的成本有多大?基本上沒有。我認為實際產生多個函式這件事並不那麼重要,但重要的是,如果你產生了一個函式的多個副本,你就必須把每一個都編譯成機器碼,這會拖慢編譯過程。strlen 字串不是應該接受 ref string 而不是按值傳遞 string 嗎?
[15:23] 其實兩者都可以。它們都能運作,這也是為什麼接受 askRefStir 很好用的原因之一。動態函式庫如何處理泛型?它們不處理。這是為什麼對 Rust 函式庫進行動態連結,甚至只是以二進位形式散布 Rust 函式庫,都很有挑戰性的原因之一。而我認為在 Swift 中,他們一直試圖穩定這類東西。
[15:54] 我們還不太知道怎麼把它用在 Rust 上。而且沒錯,你不能把它用在像是如果你想要一個 C 動態函式庫,也就是 Rust 中帶有一堆外部函式的動態連結函式庫,那些不能是泛型的。好的。所以現在我們對單態化是什麼有了概念,我想稍微談談這裡派送的實際過程。
[16:27] 所以派送的概念是……其實,讓我給一個稍微好一點的例子,我們可以在整場直播中多用一會兒。所以讓我們定義自己的 trait。我們要把這個 trait 叫做……就叫它 Hello,夠簡單了,或者我想就用挪威語的嗨吧。它只有一個方法。
[17:00] 然後假設它實際上不傳回任何東西,它就只是一個單一函式的符號,讓你用挪威語說嗨。我們可以想像我們為比如說 stir 實作了那個 trait。嗯,而它要做的就只是印出,呃,self 哎喲。嗯,然後我們要做,呃,我想就用 J 點吧。
[17:40] 嗨。啊,今天打不了字。所以這裡背後發生的事是,當編譯器試著為這個產生程式碼時,它會判定這個的型別,然後查看 str 參考型別上有哪些可用的方法。它找不到一個叫做 high 的方法。接著它查看作用域內的 trait,發現這裡有一個 high 方法,是為接收者型別實作的。
[18:18] 所以最後就變成呼叫那個。看起來沒問題。現在讓我們想像一下,我們有這個的某種泛型版本,我們拿一個實作了 high 的東西,我想是 h。而它就只會呼叫 h.high。所以這個比較棘手,對吧?當編譯器必須為這個產生機器碼時,它需要以某種方式呼叫這個方法,但它其實不知道 H 的型別。而這就是單型化發揮作用的地方,對吧?
[18:51] 實際上,最後產生出來的會是 bar str,裡面有 H、B、str。而現在,要派送這個、弄清楚這裡該呼叫什麼就很簡單了,因為我們知道具體的型別。所以這就是所謂的靜態派送。也就是說,在編譯時期,編譯器就知道實際的型別是什麼。因此,當它試著呼叫這個方法時,它就只知道那就是這個方法。
[19:22] 而它就可以直接跳過去,基本上這在組合語言程式碼裡就變成一個呼叫,去呼叫這個函式,而這個函式位於記憶體中某個已知的位置,對吧?因為它就正好是這個方法所在的地方。這樣靜態派送有道理嗎?一旦你能產生這個方法,實際上要弄清楚怎麼編譯這段程式碼就變得輕而易舉,因為這個方法其實就跟這個一樣。而這兩個都很容易弄清楚 high 方法住在哪裡。
[20:05] 所以現在我們看過了這種靜態派送,你可能會想,那麼替代方案是什麼?如果我們不想為這個產生一堆不同的副本呢?這就是我們回到動態大小型別的地方。喔,抱歉,對,這裡的 impel-hi 只是泛型的語法糖。這是等價的,就像我之前跟 Sterling 示範過的,這等價於 H 是 high。
[20:40] 這兩個是等價的。對,那麼替代方案是什麼?我們不想要這個單型化,我們不想要多個副本。或者你可能會想像這個的另一個理由是,比如說你想要,比如說你有一個向量,裡面是實作了 high 的東西。在這裡的 foo 中,我想要有一個這個的向量。
[21:21] 而我想做像是對這個向量裡的 h,呼叫 h.high。如果它們全都是同一個型別,那沒問題。但如果我想要某種集合、序列或某種集合體,裡面是實作了 high 的東西,但我不需要它們實際上是同一個型別呢?我在乎的只是它們實作了這個 trait。所以更具體地說,想像我想寫 bar,而我想接受任何是,比如說,slice 的東西,裡面是 imple high。
[22:02] 我們就從這個版本開始吧。所以對 s 中的 H,h 點 high。這運作得很好。我可以用比如 a 加上像這樣的東西來呼叫 bar。運作得很好,編譯也完全沒問題。同樣地,我可以把每一個都轉成字串。那也運作得很好。
[22:40] 喔,對,我沒有為字串實作這個。所以那運作得很好。但讓我們想像一下,我希望能夠像這樣呼叫它,這其實應該沒問題。但我做不到,對吧?比如,我沒辦法建立一個包含不同型別東西的向量。那根本不是我能夠創造出來的東西。我真正想要的,但在這個情況下,我其實不在乎具體型別是什麼。
[23:11] 我不在乎這些是字串。我在乎的只是我希望它們實作 height 特徵。這對我來說才是唯一重要的事。所以我應該能夠建立一個包含具有這種行為的東西的向量,而不必在乎具體型別。這就是我們進入動態分派和特徵物件領域的地方。書裡也有一章在講這個。讓我找一下那一章在哪裡。我用錯的順序打開了它,我真是糊塗。
[23:50] 抱歉跳來跳去。就在這裡的這一章下面。所以書裡有一章相當不錯,談到把不同具體型別的東西當作同一型別來對待的能力。他們用的另一個例子是像 GUI 的情況,你可能會有很多可繪製的東西,比如它們實作了 draw 特徵。而你可能能夠接受,你可能會想要有一個 draw 函式,它只接受某種列表或迭代器。
[24:25] 包含所有要繪製的東西。其中有些可能是按鈕,有些可能是圖片,有些可能是文字方塊,但對 draw 函式來說其實無所謂。它在乎的只是它拿到一個可繪製東西的迭代器,這跟這裡的風格很類似,對吧,我們只想接受一個我能對它呼叫 high 的東西的切片。而你需要的就是所謂的特徵物件。特徵物件就是你看到 dyn 關鍵字的地方。
[24:58] 這其實不會編譯通過。所以我要做的是,這大概就是我想要的,對吧?所以,impl,記住,是某個東西的簡寫,而這裡正是把型別實際寫出來會很有用的地方,它是這個的簡寫。而這大概就透露了發生了什麼事。Bar 對一個型別泛型,那個型別必須是 str 參考或 String。它不能兩者都是,因為它只對一個型別泛型。你可以想像我們這裡有一個 H2 high,但既然我們接受的是切片,或者說迭代器,就沒有地方可以放 h2。
[25:38] 這裡只有一個迭代器,而它只包含單一型別的項目。所以這其實行不通。某種意義上,我們想表達的是,每個東西都是 high。它沒有其他我們在意的具體型別。而事實上,如果我們這樣寫,就會得到編譯器錯誤,說讓我開個新畫面把這個調出來。它說,沒有明確 dyn 的 trait 物件已被棄用。
[26:10] 好,我們先消除這個警告。它說我們需要在這裡加上 dyn,所以我們就照做。現在它說,型別 dyn high 的值大小無法在編譯期得知。所以它指向這裡並說,在編譯期無法得知大小。trait sized 並未為 dyn high 實作。切片和陣列元素必須是已知大小的型別。這是個你以前可能遇過的錯誤。而我們在接下來這段直播剩餘部分要談的其中一部分,就是為什麼會得到這個錯誤、它代表什麼意思、修正方法是什麼、sized 是什麼意思,以及這如何與動態分派和 trait 物件相關。
[26:50] 讓我在此暫停一下,因為我剛剛丟了一大堆東西給你。我們來看看這是否說得通。所以這是一堆關於深色模式和淺色模式的討論。所以其實,我們想表達的是,你可以把這想成一種型別抹除。我們想表達的是,我想取一個東西的集合,而我只在意它們有實作這個 trait 這件事。
[27:26] 我有點想取這個 trait 的抽象概念。好,所以編譯器指出的挑戰是,在這個情況下,我們到底要從哪裡開始?好,我想我們需要先談談 sized。所以我們去看 sized trait。sized trait 沒有任何方法。它是個標記 trait。
[27:58] 那就是標記模組裡的內容。而說明只寫著,在編譯期已知固定大小的型別。現在,大多數型別都是 sized。就像如果你建立一個 struct foo,它大概就是 sized。標準函式庫裡大多數型別都是 sized。事實上,不是 sized 的型別非常少。少到事實上,你有的每個 trait bound,即使只是像 foo T,都隱含著要求該型別是 sized 的 bound。
[28:32] 而要看出原因,想想會發生什麼事,我們先把這個註解掉一下。let 並把這個註解掉一下。我只想實際取得,我想我可以更聰明地做這件事。所以我們回到最一開始那個非常簡單的 strlen 範例,對吧?
[29:05] 它會對某個實作了星號 str 的 S 泛型化。它接收那個 S,並回傳 uSize 作為 ref length。所以想像有某個東西想呼叫 strlen。嗯,strlen 接收一個就是那個 s 的引數。所以它必須被傳入某個東西。就像它某種程度上需要被傳入那個引數。嗯,它被傳入的引數必須在堆疊上佔用空間,或者必須透過暫存器傳遞,兩者之一。
[29:41] 這某種程度上意味著編譯器必須確保在產生的組譯碼中有某種程式碼,為這個引數配置所需的堆疊空間。而這要求編譯器知道該引數有多大。如果這裡的 s,我猜想想具體的實作,所以是 strlen str。這裡,這只是一個,嗯。
[30:20] 那我們就用 string 實作吧。所以 string 其實就只是,它某種程度上是兩個數字和一個指標,對吧?它是字串的長度、配置的大小,以及指向堆積上實際字串中第一個字元的指標。所以它是 size。編譯器知道這個引數的大小是三個字組,三個。可說是 use size,對吧。
[30:52] 所以我們可以輕鬆地為這個函式以及呼叫這個函式產生組譯碼,因為它知道引數佔用多少空間。你可以想像類似的情況,對吧,如果我們對回傳型別泛型化,它就需要知道實際上要在堆疊上為回傳型別配置多少空間。所以即使我們沒有特別說這裡的 s 是 sized,它基本上一直都是型別必須是 sized 的要求。因為如果不是的話,編譯器就不知道如何為它產生所需的程式碼。對吧。
[31:35] 好。那麼為什麼。為什麼當我們試著使用這個時它還是能編譯呢?嗯,din high 其實只是說任何實作了 high 的東西,就像只是某個會產生 high 而不給出具體值的東西。因為記住,我們希望這是一個可能像 string 和 stir 以及任何其他可能實作這個 trait 的型別的切片。而那些全都是不同的大小,對吧?string 是兩個數字加一個指標,str 是一個數字加一個指標,而你可以想像我們有某個型別 foo,它作為一個結構體有像一個 GB 那麼大,或之類瘋狂的東西,對吧?
[32:16] 而我們為它實作了 hi,這也是我們可能想傳入這裡的東西。所以這個 slice 沒有大小。它就只是,不是,就像如果你,slice 其實就只是一塊連續的記憶體,對吧?其中每個區塊的大小都相同。它就是一個所有元素大小都相同的陣列。但如果我們不知道它們的大小,就無法保證它們大小相同。如果我告訴你,如果我給你其中一個,那麼這裡的 din high 就沒有大小,對吧?
[32:47] 因為它可能是任何型別,而 once high 也可能是任何大小。然後我問你,給我第四個元素。通常在陣列中,因為所有元素大小都相同,第四個元素就只是指向起始位置的指標加上大約三個元素的大小,對吧?這是用來取得第四個元素的指標運算。但如果它們大小不同,你就無法產生那段程式碼。這就是為什麼它說 slice 和陣列元素必須有大小型別,因為否則這個型別就根本不合理。
[33:23] 那我們要怎麼修正這個問題?我們真的很希望能做到這件事。如果 Rust 不讓你用集合的方式來談論實作了某個 trait 的東西,那會很荒謬。而且陣列不是這裡唯一的問題,對吧?即使我們拿了,即使我們寫了,這有什麼好例子?假設我們這裡有一個 strlen2,它接受一個像 din asref str 的東西。它也有同樣的問題,對吧?
[33:57] 如果我試著編譯這個,你會看到它說同樣的話。讓我把另一個訊息關掉。它說,型別 din sRF str 的值的大小無法在編譯時期得知。Sized 沒有為 din as ref 實作。函式引數必須有靜態已知的大小。借用型別總是有已知的大小。然後它試著給你一個如何修正的建議。但這又是關鍵洞見,編譯器需要知道引數的型別有多大。
[34:31] 否則,它就無法產生函式呼叫的程式碼。所以這算是編譯器的基本要求,這些型別必須有大小。到目前為止這樣說得通嗎,像是為什麼這是個問題?你能示範給我們看實作 sized 嗎?所以 sized 會為任何能實作它的型別自動實作。
[35:04] 所以如果你做一個像 struct foo 這樣沒有欄位的東西,它是有大小的。如果你在裡面加一個 string,string 是有大小的,所以 foo 是有大小的。如果你再加一個 bool,這個型別現在仍然是有大小的。型別只要能夠有大小,就總是有大小的。例外會是,如果我做了像……而且事實上,即使我做了 foo t 而不是這個持有一個 t,它仍然是有大小的,因為記得每個 trait bound 都有一個隱含的要求,就是它必須有大小。
[35:38] 所以這裡有一種隱含的 T 有大小。這就表示 T 有大小。所以所有欄位都有大小。因此對任何 T 而言,foo T 都有大小。所以你永遠不會自己實作 Sized。它只會被當作自動 trait 使用。問題不在堆疊大小。
[36:12] 問題不在於它可能放不進堆疊。問題在於,為了呼叫函式,對,就在機器碼層級,或者把它想成組譯層級,對,為了呼叫函式,你必須在呼叫該函式時知道要為該函式的堆疊變數配置多少空間。我們可能會包含它的一些引數,或在呼叫端。當你必須為回傳值配置空間時,那個空間應該多大?基本上,這就要求你知道空間有多大,因為你無法產生配置該堆疊的機器碼。
[36:49] 有一些取巧的做法可以做到,但基本上,編譯器為了產生高效率的程式碼,必須知道這些東西的大小。讓我們看看。哪些東西沒有大小?我們談過 bare trait。所以這是如果我寫 pub fn foo,而我只說我接受一個 impl。
[37:27] 這裡的 impl 是一個 trait,很多東西都實作該 trait,而它們的大小可能全都不同。所以這沒有定義的大小。如果我在這裡寫 impl,對,impl 是 impl Trait 的簡寫。所以這個 impl Trait 有大小,因為我們會為每個具體型別取得一份 foo 的副本。而對每一份副本而言,該型別的大小是已知的。所以如果我們在這裡使用靜態派發來做單態化,這就沒問題。
[37:59] 但如果我們只是試著取 trait 本身,基本上就是說這個函式接受任何實作該 trait 的東西,這就行不通,因為這沒有大小。而這等同於寫 dyn Trait。像這樣就沒有大小。我們等一下會談到如何讓這樣的東西有大小。嗯,另一個例子是像,嗯,呃,如果我們回到我的 struct foo,呃,如果你試著讓它持有一個 str,呃,str 沒有大小,嗯,因為字串可以是任何大小,這麼說吧,如果你想的不是指向字串的指標,而是字串本身,字串本身可以是任何大小,呃,同樣地像,嗯,這,就像沒有參考的 slice,也沒有大小,因為你不知道有多少個元素。
[38:51] 所以它沒有明確定義的大小。這些是我所知沒有大小的東西中最好的兩個例子。然後任何反過來包含那些型別的東西也是。聊天室裡有很多討論,試著解釋我即將要解釋的內容,關於我們如何修正這個問題,以及為什麼你需要參考之類的。我保證我會講到。
[39:28] 太好了。所以我認為到目前為止我們大致達到的進展是合理的,看起來是這樣。所以現在的問題變成,我們要如何解決這個情況?我們希望能夠拿一個,對我們的 Sterling 2 來說,姑且稱它為 Sterling Din 吧。我們希望能夠有一個像這樣的方法,不會被單態化。但這個沒有固定大小,那我們該怎麼辦?這裡的訣竅是讓它成為一個永遠有固定大小的型別。
[40:05] 而我們做到這件事的方式,是透過某個本身對任何內部型別都有固定大小的型別來間接指向它。一個例子就是參照。所以參照永遠是同樣的大小,它就是一個指標的大小,或者在某些情況下是兩個指標,我們等一下會談到。這個確實有大小。編譯器永遠知道其中一個有多大,無論後面跟著的是什麼型別。因為這就只是一個指標。
[40:40] 如果你有一個 box 也是一樣,對吧?box 也只是一個指向堆積的指標。所以一旦我們這麼做,這個引數的大小現在就是已知的,我們就沒問題了。而這實際上就是你不做單態化、直接拿取 trait 本身的方式,就是把它放在某種指標型別後面。像是參照、像是 box、像是 arc。
[41:13] 在實務上這運作的方式是,如果你看 box 的定義,它裡面有魔法,對吧?它不是魔法,但它裡面有一堆東西。基本上,它就只是一個指標。這不完全正確,但已經夠接近了。box 實際上帶有這個定義。而這裡的問號意思是「不必」。所以它基本上是選擇退出那個自動加上的約束,也就是所有東西都必須有固定大小,它是在說對 box 而言,T 不必有固定大小。
[41:50] 這就是為什麼你可以建立一個本身沒有固定大小的東西的 box。而這之所以可行,是因為當你最初建立這個 box 時,你會做一次配置,大小就是你打算放進 box 裡的東西的大小。所以讓我在這裡寫一個 main 來示範這件事。在某個時間點,我必須做 box new,比如說 string from hello。
[42:25] 對吧?然後我可以說現在這會是一個 din as ref str。這裡應該是 x。而這裡應該是 str。然後我就可以用 y 呼叫 strlen din。所以當我建立這個 box 的某個時間點,我必須給它一個具體型別的東西。而在那個時間點,它在堆積上為那個型別配置了空間。
[42:57] 但這個箱子的尺寸仍然是已知的,因為它就只是一個指標。當我把它轉換成這個用途的箱子時,概念上它仍然只是一個指標,即使它所指向的東西可能有任意的大小。但我們實際傳給這個函式的引數確實有大小,因此我們可以產生相關的程式碼。這樣說得通嗎?為什麼透過這種型別進行間接指向,而間接型別的大小是已知的?這樣說得通嗎?
[43:37] 我們也會談到 trait 的組合。我看看。我保證我們會講到多重 trait。你不能直接把 BoxedInAsteroidStir 放在 X 上嗎?對,所以你也可以這樣做。AsteroidStir。這樣也沒問題。但即使如此,你仍然必須提供一個有確定大小的具體型別給 Box New。
[44:16] 什麼時候我們該用 box 而不是引用?比如說你什麼時候會選這個而不是那個?這沒有硬性規定。一般來說,box 的優點是它是靜態的。所以即使呼叫者的堆疊框架消失了,你仍然可以繼續使用它。所以這就跟一般情況下你什麼時候會選 box 而不是引用是一樣的。那我也可以把堆疊的引用傳給函式嗎?對,完全正確。
[44:47] 所以你也可以這樣做,讓我在下面這裡做。所以我完全可以這樣做,然後 Sterlendyn,為什麼?對。所以這個,假設我有一個 din2 接收這個,而這個可以呼叫 din2。
[45:25] 為什麼這個會報錯?因為 box 也有一個星號方法。這就是為什麼需要雙星號。對,所以你看,我可以對堆疊上的東西做同樣的事。我可以建立一個某種透過指標間接指向的東西,然後把它傳給一個接收引用的函式。
[45:59] 而事實上,我想我甚至可以這樣做。對,這樣沒問題。為什麼那個不行並不是非常重要。所以我們剛剛建構出來的東西稱為 TraitObject。它是一個只具有代表某個 trait 這個屬性的物件。所以這就是 TraitObject 的本質。它們就是只會表現為某個底層 trait 的東西。
[46:35] 這是一個 TraitObject,而這也是 TraitObject。外層包裝的型別是什麼並不重要。Box 算是一種指標型別。對,box 是一種指標型別。我可以把 trait object 轉換回它原本的具體型別嗎?我會說不行,但技術上來說有時候可以。但一般來說,不行。你可以把它想成,這本質上就是型別抹除。
[47:08] 技術上來說,你可以透過不安全的 transmute 之類的方式還原回去,但一般而言,一旦你把它變成 trait 物件,你就抹除了它原本是什麼型別的資訊。不過沒錯,unsafe 周圍有一些魔法,any trait 周圍也有一些魔法可以使用。但一般而言,你應該忽略那些。另外要注意的是,當你這麼做時,你只保留了使用這個 trait 的能力。你抹除了關於具體型別是什麼的所有其他知識。
[47:39] 所以對於裝箱成 ASRF 的 stir,你唯一能做的就是對它呼叫 ASRF,別無其他。這裡也是一樣。我們待會兒會深入探討原因。好。所以這帶出了一個有趣的問題。讓我們拿這個例子來說,把這個設為二、這個設為一,然後把它們對調,這樣仍然能編譯。現在讓我們想想,當編譯器必須為這個函式產生機器碼時,實際上會發生什麼事。
[48:15] 在某個時間點,它必須實際進行編譯並產生組合語言碼,而這些組合語言碼接著可以轉換成可執行的機器碼。所以這裡的 S 是某個實作了 Sref 的型別。事實上,讓我們回到我們的 high trait。那會稍微好一些。所以讓我們回到這裡,假設我想要一個 sayHi,它接收一個 dinHi、不回傳任何東西,就只是呼叫 Hi。對吧?所以這會是,這接收 Hi trait 的 trait 物件。但當編譯器在這裡產生程式碼時,它並不知道 s 是什麼型別。對吧?
[49:01] 它就只是一個 trait 物件。它真的就只是一個指標。那麼它要如何呼叫 high 方法呢?還記得嗎,在泛型的情況下是靜態的 H。在這種情況下,我們實際上會為每個具體型別取得一份這個的副本。
[49:37] 所以實際上,這會變成這樣。而對於這個具體實作,產生機器碼是輕而易舉的,因為這真的就只是像一個組合語言的呼叫,指向無論是什麼,指向這一行,指向第 6 行。它實際上不是行,而是二進位檔中的記憶體位置,但你懂我的意思,對吧?編譯器在編譯期就靜態地知道這裡該往哪裡去。
[50:10] 不過對於動態的情況,我們要呼叫什麼呢?我們不知道這是 str 還是 string,對吧?所以我們不知道該產生這個的位址、這個的位址,還是完全另一個東西的位址。那麼這會變成什麼機器碼呢?嗯,這就是我們要深入探討動態派發和 V table 或虛擬派發表的地方。所以建構 trait 物件的訣竅在於,其實「box 的參考就只有一個指標寬」這個說法並不完全正確。
[50:48] 它其實帶有一點關於所指型別的額外資訊。所以這裡,讓我們回到,回到 Rust 書。Rust 書有一章在講動態大小型別與 size trait。這是在進階型別那一章底下。而它談論的其實甚至沒有我們想談的那麼多。這裡。
[51:22] 我們改用 Rust 參考手冊。Rust 參考手冊關於動態大小型別的說法是,大多數型別都有固定大小,在編譯期就知道,並實作 sized trait,就像我們談過的。大小只有在執行期才知道的型別稱為動態大小型別,非正式地稱為 unsized 型別。而 slice 與 trait 物件就是動態大小型別的兩個例子。之所以只有在執行期才知道,是因為在編譯期我們不知道這會是什麼型別。只有在執行期我們才會知道。
[51:54] 而我們可以,為了讓這件事更具體一點,想像我有一個 main 函式,其中如果 rand,我沒有亂數,random 是四。如果 random 是四,那就對這個呼叫 say hi,否則對來自 world 的字串呼叫 say hi。對吧?
[52:30] 而讓我們想像 random 比 4 更隨機。你在執行期之前不會知道。假設這是從使用者讀進來的。在編譯期,你不知道這裡實際會用哪個型別。它只有在執行期才由某些在編譯期無法預測的輸入決定。對吧?所以這就是為什麼這是在執行期決定的。而它說,指向動態大小型別的指標是有大小的,但大小是指向有大小型別的指標的兩倍。
[53:09] 所以指向 trait 物件的指標也會儲存一個指向 V table 的指標。而這就是我們進入什麼是 V table 的地方。嗯,當你有一個 trait 物件,像是 dyn pi 這樣的東西,參考裡實際儲存的是一,一個指向實際具體實作型別的指標,以及二,一個指向被參考 trait 的 V table 的指標。
[53:48] 那麼什麼是 V table?V table 或虛擬派送表是一個小資料結構,裡面有指向該型別之 trait 每個方法的指標。所以在 high trait 的具體案例中,假設我們有一個 dyn high,V table 會有點像你可以把它想成一個 high V table 結構體,只有一個成員,就是 high,它是一個指向 Fn 的指標,一個 Fn,它本身接受一個指向 T 無論是什麼的指標。
[54:45] 所以基本上,每個被轉換成特徵物件的具體型別,最後都會建構出一個不同的 V table。所以當我們一開始有個,比如說我們有一個 str,而我們想把它轉成 dyn high,實際被建構出來的會是,比如說我們有一個 um,嗯,第一項會變成指向該 str 的指標。
[55:16] 而第二項會變成一個 high Vtable,其中 high 是 str as high、high,以及一個指向它的指標。當你進行這個轉換時,編譯器知道它必須建構這個 Vtable,並把該 Vtable 的位址塞進那個參考裡。
[55:48] 所以這個參考包含兩樣東西:指向實際型別的指標,以及指向編譯器在這個特定轉換過程中產生的 Vtable 的指標。所以每個被轉換成 TraitObject 的型別,都會有一個這樣的 Vtable。而現在當編譯器試著產生這段程式碼時,它實際產生的會像是 s.VTable.High s.Pointer。
[56:23] 所以如果有人傳入的是,比如說,一個 string,它就會有不同的 Vtable。所以 s.Vtable 會是不同的指標。所以在這種情況下,這裡就會是 str 的 high 在哪裡?像是第 6 行,對吧?所以這會是指向第 6 行的指標。但如果我們改成,我等一下會停下來讓大家提問。如果這裡改成從 string 轉成 dyn high,它就會是指向該 string 的指標,以及 string as high,也就是上面第 12 行的這個方法。
[57:06] 換句話說,這段被產生的程式碼無論傳入哪種型別都能運作,因為我們是透過 V table 間接存取,而每個型別都有自己獨特的 V table。好,這一口氣丟給你們的東西有點多,但希望還不算太糟。我們來看看。
[57:45] V table 本身是在編譯期靜態建構的,還是也會動態配置?V table 是……V table 是在編譯期建構的,它們是靜態建構的。所以一般來說,第二部分……所以這就是所謂的胖指標或寬指標,因為它裡面有兩個指標,而不只是一個。所以每當你看到這個,它其實就是一個寬指標。而一般來說,裡面第二個指標永遠會在靜態時就知道,因為它是由最初的建構所決定的。
[58:23] 特徵物件的。我說「一般來說」的原因是,技術上你可以在執行時即時建構它。這裡的呼叫端並沒有任何要求它必須在靜態時就知道。所以你可以想像手動建構一個 vtable。而這會被用到,我們其實稍後會稍微談到。Refster 也包含字串切片的長度。
[58:56] 是的。所以一般來說,這實際上會是這樣。所以它不是指向實際字串的指標。它實際上是指向 str 參考的指標,而該參考本身持有長度。我們能不能用某種方式除錯列印 Vtable 結構?我不知道有什麼方法能讓編譯器列印它的 Vtable 結構,但它基本上就是這個。
[59:33] 它就只是,對這個 trait 物件所對應 trait 的每個方法都有一個成員,其中每個成員是……每個成員都是對應的方法,而值是指向該方法針對具體型別的實作的指標。那麼,為什麼不接收 self 的 trait 函式不是物件安全的?編譯器難道不能直接產生一個不使用 self 的 fn mute self 嗎?
[1:00:08] 我們等一下會談到那個。每次我們建立實例時,它都會建構一個新的 V table 嗎?不會,V table 通常是為該型別靜態建構的。它不會被動態建構。相同的 V table 會被偵測出來嗎?不會,這些沒有去重。事實上,它們被保證不會重複。
[1:00:43] 如果你為兩個不同的型別實作一個 trait,那麼這些實作即使包含相同的程式碼,在原始碼和產生的二進位檔中仍然是不同的位置,因此會有不同的位址。多個 trait 的 trait 物件我們等一下會談到。所以 box din 是一個薄指標,指向一個指向物件的寬指標。不對,如果你有一個 box din height,那個 box 本身就是一個寬指標。
[1:01:22] 所以 box 算是稍微特殊的型別。其實它沒那麼特殊。就只是 box 內部包含一個 mute dhinhi。而 Rust 編譯器知道對於參考和指標,如果它們是 trait 物件,它們實際上是寬的 2。所以 box 並不特殊,但指標型別是。所以 box.dynhi 本身就是寬的。你不會多出一層間接。對,我們也會談到 trait 物件的 nightly API。
[1:02:13] 好,所以我想我們現在已經到了大致說得通的地步。所以 trait 物件比完全泛型受到更多限制,有幾個原因。舉例來說,讓我們想像你想要有一個……hubfn baz,它接收一個 s,假設是 din,比如說,hi 加上 sref stir。
[1:02:58] 然後我們要做 s.hi。接著我們也會說,let S 是 S 點 S ref。然後我們要再做一次 S 點 high,因為我們知道字串本身有實作 high。我想這可能有點令人困惑。也許我應該只做 len。這裡的編譯器說,喔,這有歧義。好,讓我們消除歧義。這其實和討論不太相關。
[1:03:33] 它還是不讓我這樣做,為什麼不行?我是不是得這樣寫才不會有歧義?不,好吧,我就先假設這個語法行得通好了。基本上我想表達的是,我想要一個包含兩個不同 trait 的 trait 物件。這其實無法編譯,先忽略解析錯誤,其實有個更大的原因讓它行不通,那就是:要讓這件事成立,我們必須同時知道 high 方法在哪裡,以及 asref 方法在哪裡。
[1:04:18] 但這兩個方法分別存在於兩個不同的 vtable 中。一個是具體型別 high 的 vtable,另一個是具體型別 asref 的 vtable。所以我們真正需要的,不只是兩倍寬的指標,而是三倍寬的指標。一個指向資料的指標、一個指向 high 的 vtable 的指標,還有一個指向 asref 的 vtable 的指標。這是有可能的,並沒有什麼本質上不可能的地方,但這意味著當你加入更多 trait 時,這個參考的大小就會不斷增長。
[1:04:55] 而那大概不是你想要的。你可能會說,編譯器難道不能直接為這個組合產生一個 vtable,然後傳進去嗎?理論上它是可以這麼做。Rust 編譯器目前並不會這樣做。我也不知道有相關的提案。部分原因是你可以用另一種方式繞過這個問題,就是宣告 pub trait high asref,並要求該型別同時是 high 和 asref str,而且它本身沒有自己的方法。
[1:05:28] 現在我就可以這樣做了,對吧?因為現在只有一個 vtable,而這個 vtable 就是 high asref,編譯器知道當它要為這個 trait 產生 vtable 時,必須包含這兩個 trait 的所有方法。所以這個 vtable 會比較大,因為它會同時有 high 方法和 asref 方法。所以我認為這件事一直沒有進到 Rust 本身,部分原因是你可以自己選擇這樣做。而透過不自動把加號變成更大的 vtable,你基本上是在告訴開發者:這可能不是你原本的意思,但如果真的是,你可以改用這個做法。
[1:06:12] 我同意這裡的編譯器錯誤訊息應該可以更好,對吧?有些人,像是 Esteban Cooper,就提到,也許我們可以告訴……使用者他們可以在這裡產生自己的 trait。我想有人寫了,我想是 I plus s ref。
[1:06:52] 好,我們來看看這是不是真的。對。好。所以,這就是取得正確編譯器錯誤的方法,也就是只有自動 trait 可以作為 trait 物件中的額外 trait。而這裡你有一個例子,是兩個不同的 trait,它們都不是自動 trait。我們等一下會談到那個。而這裡它確實給了我們剛才談到的建議,對吧?考慮建立一個新 trait,把這些全部作為 super trait,並在這裡改用那個 trait。它還指出像 send 和 sync 這類自動 trait 是沒問題的。
[1:07:27] 基本上這裡的想法是,對於標記 trait,比如說如果我想寫 high 加 send,send 沒有任何方法。所以 V table 是空的也沒關係。因此我們不需要儲存 V table 的那個額外部分,因為裡面沒有任何方法。所以這就是為什麼可以有沒有方法的額外 trait。我不認為你可以用你自己的。比如說如果我做了一個 Fuchs trait,然後我說這個加 Fuchs,我不認為那會可行。
[1:08:00] 但一直有一些提案,想要有一個標記註解來宣告某個 trait 永遠不會有方法。但那不是我們目前有的東西。所以至少目前為止,這就是你應該採用的做法。太好了。
[1:08:34] 好。所以這就是 trait 組合的運作方式。但那不是 trait 物件稍微受限的唯一例子。另一個例子是,讓我們想像我們為 high 加了一個,其實,讓我們先說我們加了一個關聯型別。我們叫它 name。而我們其實沒有用它做任何事,我們只是加了一個。程式碼已經無法編譯了。為什麼無法編譯?
[1:09:05] 嗯,關聯的……喔,那是實作。讓我來做那個。所以這會是 type name 等於 unit。就把它用在兩者上,因為我們其實不在乎那個型別。對,所以這裡說必須指定來自 trait high 的關聯型別 name 的值。所以這裡說,在我們接收 dyn high 的地方,我們其實需要指定關聯型別。
[1:09:39] 我們不能只說我們接收任何 high,不管它的關聯型別是什麼。這裡的原因是那個資訊無法被捕捉在 V table 裡,因為這是一個型別。它在二進位檔裡沒有位址。它沒有任何東西可以讓我們放進 V table。因此,這無法直接與 trait 物件搭配運作。相反地,你必須說我接收一個 high,其中 name 是這個。而我想我們需要在下面這裡做同樣的事。
[1:10:15] 然後這樣就行了。因為現在我們有一個專門針對任何實作 high、且關聯型別為 name 的 V 表。所以這樣沒問題。我們把這個還原,因為這不是個很有趣的改動。另一個或許更有趣的情況是,假設我們想要一個……我們要怎麼稱呼它?我們就叫它 weird 吧。我們會有一個什麼都不做的 weird 函式。
[1:10:48] 沒有人需要實作它。你會看到這也無法編譯。cargo check 出現錯誤。我們把這段縮小一點,希望這樣能比較容易理解。希望它還是可讀的。喔,這真是冗長。我把組合 trait 那部分註解掉,讓錯誤訊息好看一點。好,所以這裡說 trait high 無法被做成物件。
[1:11:24] 所以當我們說 dyn high 時,基本上它是在告訴我們 high trait 不是物件安全的。也就是說,它無法被轉成 trait 物件。它說一個 trait 要物件安全,就必須允許建立 V 表,讓呼叫能被動態解析。這就是我們目前一直在旁敲側擊的東西。特別是這裡說,這個 trait 無法被做成物件,因為關聯函式 weird 沒有 self 參數。不過它並沒有真正說明為什麼這是必要的。但我們試著把它推導一遍。
[1:11:56] 所以再一次,假設在下面我們的 sayHi 裡,對吧?我們現在試著呼叫 s.weird。那麼想像一下,如果我們寫了這段程式碼,編譯器會怎麼做?嗯,我們其實沒辦法寫這段程式碼,對吧?因為 weird 沒有接收 self。它沒有接收任何指標。而我們也不能隨便亂建一個指向它的指標,因為那意味著我們需要有一個有效的實例,才能有指向它的指標。
[1:12:28] 所以這其實就等於是在說 hi 冒號冒號 weird。這不用我說也顯得很怪,因為我們在這裡到底是對哪個型別呼叫 weird?這裡沒有任何東西指定我們想要哪個實際的 weird 實作。在這個特定情況下,因為它提供了預設實作,你可能會覺得這不是問題。但要是有一個針對 string 的 weird 實作呢?
[1:12:58] 那個實作和 trait 上的不同,而這是允許的,對吧?你可以覆寫預設實作。那麼這要怎麼知道該呼叫 str 的那個、trait 的預設那個,還是某個完全不同的?它不可能放在 V 表裡,因為這裡沒有 S,對吧?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 table 的方式,你可以這樣想。它是在說這個函式不應該被放進 V table,而且關鍵是它不應該能透過特徵物件被呼叫。這意味著在這裡,讓我把 static 版本拿掉,因為它們只是擋路。這意味著現在程式碼可以順利編譯。我可以呼叫 hi,我可以為它建立特徵物件。但如果在這裡,事實上,我可以更進一步說,假設這個確實有 self,但我想要退出。
[1:15:22] 那麼這仍然可以編譯,我仍然可以為它建立特徵物件。但假設我試著在這裡呼叫 weird。編譯器會告訴我 weird 方法無法在特徵物件上被呼叫,因為該方法有 sized 要求。所以這就是針對任何給定函式退出、不讓它被包含進來,以確保該特徵維持物件安全的方式。你也可以說整個特徵不應該能被轉成特徵物件,方式是寫上 where self 是 sized。
[1:16:01] 所以如果你這麼做,你基本上就是禁止將這個特徵當作特徵物件使用。在實務上很少見到這種情況。通常特徵就只是因為裡面的方法而不是物件安全的。主動選擇禁止特徵物件很罕見。有時候人們會為了……向後相容的理由這麼做。就像如果你知道你之後可能會加入非物件安全的方法,你可能會預先加上這個,但這相當罕見。
[1:16:36] 好,到目前為止的限制都還說得通嗎?關聯型別的問題也會發生在靜態分派上嗎?不會。原因是使用靜態分派時,因為它會被單態化,你實際上知道任何給定函式實作的具體型別。s 冒號冒號 weird 是有可能的。
[1:17:10] 所以這是我們還在使用 fn 奇怪寫法的時候,對吧?然後假設我們這裡也有一個覆寫。現在假設你希望能做到,比如說我們加上了像這樣的特殊語法,表示對於 s 這個型別,要呼叫名為 weird 的方法。你可以想像 weird 被納入了 trait 物件的 vtable 中,但它知道不要用 self 引數來呼叫它。這裡的挑戰在於,這有點奇怪。
[1:17:45] 如果你終究需要該型別的實例才能呼叫它,那它為什麼不直接接收 self 就好?傳統的例子是,weird 實際上叫做 new 或類似 new 的東西,對吧?在那種情況下,如果你已經有該型別的實例,你根本就不需要呼叫這個方法。它直接接收 self 就好了。所以我同意,像這樣的東西或許是可行的。我認為實務上,它通常就是沒那麼有用。
[1:18:19] 這就是為什麼它一直不是優先事項。可能還有更深層的原因讓它沒被加入。我不確定。嗯,嗯,where self: sized 是否也禁止為具體的 DST 實作該 trait 呢?你知道嗎,這是個好問題。所以問題基本上是,如果你有 where self is sized,我可以為 box dyn 實作該 trait 嗎?
[1:18:58] 舉例來說。我相信可以。我說這應該可行的原因是,因為,對,這現在行不通,因為它不能是 trait 物件,但我相信你仍然可以有這個實作。為什麼會這樣?喔,對,因為它是 box。所以我們需要有雙重 sref。這沒問題,因為這不是動態大小的型別。
[1:19:35] 再次強調,當你把它包在指標後面時,它現在就有大小了。它不是動態大小的。所以即使你在 trait 上有 self-sized,它也不會阻止這件事。關聯型別的限制感覺很奇怪,因為關聯型別的重點就是,對於任何給定的具體型別,只會存在一個。所以 vtable 難道不應該知道關聯型別應該是什麼嗎?比如說,它不能有指向該型別的指標,但 trait 的實作在編譯時應該知道該型別是什麼。
[1:20:07] 對,所以問題在於型別被抹除了。剩下的只有 vtable。所以你無法從 vtable 得知原本的具體型別是什麼。這有個例外,就是 any trait。any trait 有一個方法會回傳……會轉換成它原本所屬具體型別的描述子。如果你沒聽懂,沒關係。忽略它就好。但基本上,有一些方法可以稍微繞過這個限制。但基本上,trait 物件是型別抹除的。
[1:20:38] 就像你無法保留它過去型別的資訊。喔,你是指像 str 或 u8 這樣的型別。不,你做不到。當你使用 where self is sized 時,Self 必須是 sized。TraitObjects 還有一個限制,就是方法不能是泛型的。關於這點,與其繼續研究我們那個奇怪的高階 trait,我實際上要去看標準函式庫裡的 fromIterator trait。
[1:21:16] 所以 fromIterator trait 是例如 Vec 所實作的。collect 就是這樣運作的,Vec 實作了 fromIterator。而當你有,嗯,如果我們看 iterator 的 collect,我想這是最好的說明方式。對 iterator 呼叫 collect 要求收集的目標型別實作 from iterator。這就是為什麼你可以有一個 iterator 並收集進 vec,因為 vec 實作了 from iterator。不過 from iterator trait 有點奇怪。這個 trait 的 A 型別是 iterator 項目的型別。
[1:21:55] 但你也會看到 from iterator 型別本身接受一個 T。這裡的 T 是 iterator 的型別,對吧?因為它必須是 vec,例如。它不在乎 iterator 是什麼。它可以是,你可以從任何型別的 iterator 建構 vec,只要,嗯,你可以從任何項目為 T 的 iterator 建立 vec T。這嚴格說來應該叫 I 代表 iter,但這不是很重要。這裡,a 是你最終會得到 vec 的那種東西。
[1:22:30] 所以如果這個 a 是,比如說 bool,你最終會得到一個 bool 的 vec。而 t 是 iterator 的型別,可能是像,我不知道,像 HashMap 迭代器之類最終成為的型別。不過這對 Trait object 造成了問題。讓我們想像我們試著針對這個寫程式碼。所以我要先把這個擦掉一下。事實上,我要寫一個新的。把這個檔案剩下的部分全擦掉。然後我要有像是,我們在這裡要做什麼,來做 collect 吧。
[1:23:09] 標準的 iter from iterator,我們要接受一個 from iterator of bool。然後我們要回傳一個 vec of。然後我要做 s 點 collect。喔,我做了什麼?我做了奇怪的事,對吧?太好了。所以這看起來應該沒問題,對吧?我接受任何可以,我接受。
[1:23:42] 嗯,實際上,這因為幾個原因而很奇怪。也許 fromIterator 在這裡是個不好的例子,因為它也不接受 self。所以它實際上無論如何都要求 self 是 sized。Extend 是更好的例子。讓我在這裡找出 extend。太好了。所以我們改用 extend。而且它必須接受一個可變引用。所以我們要做那個 mut v 是 back new,然後我們要做 v 點 extend。
[1:24:18] 其實,我們根本不會那樣做,我們會把這個當作 V,我們會做 v dot extend,然後只給它一次 true。所以我們就只用一個 bool 來擴展它,加入 true。所以我們接收任何可以用 bool 迭代器擴展的東西。然後我們試著用一個只產生單一 bool 的迭代器來擴展它。
[1:24:49] 所以我們就只要加入 true,我們會把 true 附加到我們拿到的任何東西上。這裡也一樣,它告訴我們 trait extend 無法被做成物件,因為 extend 不是物件安全的。如果我們看 extend,從我們目前看到的內容來看,這並不會立刻說得通。對吧?所以再一次,它對迭代器項目的型別是泛型的。這沒問題。Extend 接收 self。所以我們確實有東西可以放進 V 表。而給定一個實例,我們大致知道怎麼呼叫這個方法。但再一次,注意它對迭代器的型別是泛型的。
[1:25:23] 這就是它變得非常奇怪的地方。你可以想像在 vec 內部,對吧,會有 imple t、extend t for vec t。而它會有這個實作。我乾脆把這個叫做 I,因為我覺得這樣比較有幫助。而誰知道這裡面會有什麼,對吧?
[1:25:58] 對,就只是為了消除那個警告。呃,我要這樣做。嗯,我想稍微更有幫助一點。我的 vec。這個實作會存在於標準函式庫的某個地方,對吧?只是換成 vec 而已。但這個方法是泛型的。所以我們從單型化的討論中知道,實際上在編譯時期,我們不會只得到一個 extend。
[1:26:35] 我們會得到這個方法的多個副本。對吧?我們會得到像是 extend rule 接收……現在,一個 extend,我猜是 HashMapIntoIter,它接收一個標準集合 HashMapIntoIterator。對吧?而事實上,甚至不止於此,因為整個 impl 是泛型的,我們實際上會得到這個。
[1:27:13] 那就是實際被實作的方法。或者說是由編譯器產生的,假設有人試著用 bool 的 HashMap 迭代器來擴展。沒有單一的 extend。每一種迭代器和項目型別的組合都有一個。所以放進 V 表的是什麼?我們已經確定我們想要 extend bool。
[1:27:44] 所以這樣很好,對吧?所以只有,我們不必考慮這裡的 T,因為我們已經選擇了那個 T。但對於 extend 本身,我們在 V 表中,真的需要有一個指標,指向這個針對 bool 的迭代器型別的 extend。但這並沒有在函式的型別中表達出來。而且我們甚至沒有辦法表達它。對吧,你可以想像像是,這些 extend 的實作是標準 iter one spool 或之類超級奇怪的東西。
[1:28:26] 但就它被寫出來的方式而言,這裡沒有任何東西說明我們希望 Vtable 指向標準 iter once 的 extend 實作。問題就出在這裡。當編譯器試圖產生這段程式碼時,並沒有指向 extend 適當實作的指標。因此,V 表無法被產生。你無法為 dinExtend 產生 V 表,因為它會有無限多個項目,每個可能的 extend 實作各一個。
[1:29:02] 因此,答案就是 dinExtend 不可能存在。你無法為 extend 建立特徵物件。好,這樣說得通嗎?這是個有點複雜的解釋,但希望這裡一切都能串連起來。嗯,Rossi 能不能為每個呼叫 extend 時所用的 T,把單型化的 extend 版本加到每個實作 extend 的型別上?這很誘人,但並不總是可行,對吧?
[1:29:36] 所以想像你正在編譯這段程式碼,但,嗯,我的意思是,即使只是標準函式庫,對吧?標準函式庫有一堆 extend 的用法,但在依賴那個 crate 的 crate 中,它們可能會用更多型別來呼叫 extend。所以 V 表的大小,比如當你編譯最底層的 crate,可以這麼說,也就是標準函式庫,基本上,那會意味著標準函式庫中 din extend 的 V 表,與 crate 中 din extend 的 V 表不同。
[1:30:12] 更上層的其他 crate,因為有更多你可能想用的迭代器實作。所以你現在最終會得到許多不同的 vtable 實作,或許多不同的 dinExtend vtable。而那就像是會造成組合爆炸之類的問題。而且那也意味著你無法把標準函式庫中的 dinExtend 傳給更上層 crate 中接受 dinExtend 的東西,因為它們的 vtable 型別不同。好。
[1:30:54] 所以這就是為什麼你不能有…… 為了讓一個 trait 具備物件安全性,它需要…… 不能有泛型方法。它需要,它的所有方法都需要有一個包含 self 的接收者。還有另一個要求,就是這個 trait 不能有回傳 self 的型別。所以如果我們在這裡稍微往回推一點,說 clone,而我們想拿一個是 dyn clone 的東西,我們就只是要呼叫 clone,因為那是我們對 dyn clone 唯一能做的事。
[1:31:37] 對吧?如果你有一個 dyn clone,你實際上只能做這個 trait 允許你做的事,而 clone 唯一允許你做的就是 clone。所以這表示 clone 這個 trait 不能被變成物件。這是我們現在已經看過不少次的錯誤。你不能這麼做的原因是因為 clone 這個 trait,對吧,有一個 fn clone,它接收 self 並回傳 self。好,所以假設我說 let x 是 v.clone。x 的大小是多少?dyn clone 就是任何可被 clone 的型別。
[1:32:16] 而它應該回傳 self,而不是參考。所以它不應該回傳一個參考 DynClone。它應該在給定參考的情況下回傳 self。所以這某種程度上表示它應該回傳 DynClone,因為那在這裡就是 self。因為我們已經抹除了具體型別。但 DynClone 不是 sized。所以這會表示這個方法的回傳值不是 sized。而一個……函式的回傳型別必須是 sized,我們才能為它產生程式碼。
[1:32:49] 因此,這行不通。所以你不能有回傳 self 的方法,才能讓一個 trait 具備物件安全性。這就是為什麼你不能做 clone。現在,有些情況下你有一個 trait,就像我們談到 high 時說過的,你可能有一些方法是物件安全的,而且本身仍然有用,但你有一堆其他方法會讓這個 trait 不具備物件安全性,可是你想把它們包含進來給那些不經過 trait 物件的型別用,純粹是因為方便。
[1:33:23] 而事實上,一個很好的例子就是如果我們看 iterator 這個 trait。所以 iterator 這個 trait……對吧,有關聯型別 item,那沒問題,它有 next,而 next 是物件安全的,但它也有一堆方法,像是 chain,那是泛型的,它有 enumerate,那會回傳 self,它有 by ref,那會回傳 mut self。
[1:33:56] 它有 collect,那依賴於 from iterator,我們已經知道那不是物件安全的。那 iterator 怎麼會是物件安全的?因為它就是。如果我在這裡說,然後我說我想拿一個 dyn iterator,其中 item 是 bool,我們 collect。哎呀,iterator。嗯,我不能呼叫 collect,因為這個方法不能在 trait 物件上被呼叫。
[1:34:30] 但我可以呼叫 next。我可以在這個東西上呼叫 next。靜音,不然它不會運作。這樣就正常了。而迭代器 trait 達成這件事的方式是,如果你仔細看,你會發現,如果我實際進到迭代器 trait 的原始碼,你應該會看到這個,你只要在這裡找到。
[1:35:03] 所以比如說 count,它會消耗 self,對吧?所以它不允許放在參考後面,那會讓它變成 sized,它有 where self is sized。如果你往下捲到 last,也是一樣,self is sized。如果我們看 chain,你會看到 chain,它是泛型的,所以通常會讓這個 trait 變成非物件安全,它有 where self is sized。而這麼做的原因是,你基本上可以,這跟我們對那個奇怪函式做的事一樣,對吧?你可以用 where self is sized 這個界限來說,為了把這個 trait 當作 trait 物件使用,忽略這個函式。
[1:35:41] 基本上,不要試著把它放進 V table。這代表的是,如果有人有一個 trait 物件,他們就不能呼叫這個方法。但如果他們沒有 trait 物件,如果他們實際上有一個 vec 迭代器,或者他們有具體型別,那他們就可以呼叫這個方法。所以這是一種方式,讓一個 trait 有一些好用但不錯的方法,卻不會讓整個 trait 變成非物件安全。嗯,接收者可以是任何包含 self 的東西嗎,還是必須是 ref self 或 mut self?
[1:36:16] 嗯,所以這的規則其實是,呃,我把它放在哪裡?我在某處有開著。給我一下。這裡。所以這是來自 Rust 語言參考關於物件安全的部分。而事實上,到目前為止我們已經涵蓋了大部分這些東西。所有 super trait 也必須是物件安全的,對吧?因為我們從所有 super trait 的聯集建構 V table。Size 不會是 super trait。
[1:36:47] 所以那就是,如果我們要求 self 冒號 sized,它就不是物件安全的。不能有任何關聯常數。這同樣是因為,你沒有地方可以放這些常數。理論上,也許你可以把它們放進 V table,但這樣 V table 會變得非常大。而且 V table 裡的值也不再全都是函式指標。它們可能是任意大小的東西。所有關聯函式必須可以從 trait 物件派送,或被明確標示為不可派送。
[1:37:19] 所以可調度函式要求它們沒有型別參數,因此它們不是泛型的。它們必須是不使用 self 型別的方法,對吧?具體型別,除了接收者的型別之外。所以我們不能有回傳 self 的東西,例如。它不能有接收者,除了以下型別之外的任何東西,對吧?所以它可以是對 self 的參考、可以是對 self 的可變參考、可以是 box self、RC self、ArcSelf 或 PinSelf,更確切地說是 PinToSelf。所以基本上任何在指標後面的東西,任何可以接受、任何可以將非 sized 的東西轉換為 sized 的東西。
[1:37:55] 你可以看到這明確排除了 where self is sized 約束,這樣即使某些方法不是物件安全的,你仍然可以擁有物件安全的 trait。這些是非可調度函式。嗯,函式庫作者是否應該總是考慮為非物件安全的方法加上 where self is sized,以防下游有人想將它用作 trait 物件?我認為是的。嗯,這有點取決於你的 trait 是否可用。
[1:38:28] 所以如果你的 trait 不能作為 trait 物件使用,比如想想 clone,對吧?那麼當然,你可以為 clone 方法加上 where self is sized,這樣人們就可以建立 trait 物件 clone,但他們甚至無法呼叫該 trait 的主要函式。所以這可能不值得。但我確實認為,一般來說,如果你有一個 trait,它是有用的,即使你……只能呼叫物件安全的方法,那麼為其他方法選擇退出可能是有意義的,這樣整個 trait 就是物件安全的。
[1:39:14] iterator 的 last 有 sized 限制嗎?我認為 iterator 的 last 有。嗯,last 有 where self is sized 的原因,你在這裡看不到。它被 rust doc 隱藏了,嗯,是因為它的接收者。它不經過參考。它消耗 self,嗯,這意味著它接受 self,嗯,而 self 是一個 dyn iterator,它不是 sized 的,而函式參數必須是 sized 的。
[1:39:47] 因此 last 不能透過 trait 物件呼叫。還有一件事我沒告訴你。嗯,有很多事我沒告訴你,但至少有一件關於 trait 物件的事,那就是 trait 物件有一個小秘密。所以讓我們說我有 pub trait。實際上,讓我們這樣做。drop 實際上是物件安全的。
[1:40:19] 你可能會覺得這很奇怪。就像如果一個物件你唯一能做的事就是丟棄它,那它真的有那麼有趣嗎?事實證明,這在幾種情況下很有用。例如,我知道 Crossbeam 就是這麼做的,當你想要做垃圾回收,但不想立刻丟棄物件時。你想把它們串成像是連結串列之類的東西,然後定期去回收所有垃圾。因為你想在一個型別裡存放許多可能不同的東西,你需要 TraitObjects。所以它就只是把 mute 存在 drops 裡,或者我認為技術上是 boxed in drops,但效果相同。
[1:40:56] 你實際上無法用它做任何事。但在這裡,當 v 離開作用域時,dropDrop 會透過 btable 被呼叫。這應該會讓你覺得,等一下,因為讓我們用我們的 sayHi 來看看。我們取 dinAsRef.stir。或者其實,我們甚至用 boxed 來看看。
[1:41:30] 這樣比較好。當 s 離開作用域時會發生什麼事?想一下這個。我們得到一個 box,所以我們在堆積上有一塊記憶體配置。我們可能會在這裡用到它,可能會呼叫 s.asref,那可能是 high,隨便啦。但當這個函式返回時,我們會丟棄 s。但當我們丟棄一個 box 時,我們必須釋放記憶體。但這是一個 trait object,所以它唯一有的方法就是 asref。
[1:42:06] 這個問題的答案是每個 Vtable 都包含 drop。你可以把它想成這裡有一個隱含的 drop,但實際上,任何 TraitObject 的 Vtable 都包含一個指向具體型別 drop 函式的指標,因為這是必要的。它技術上也包含一點額外資訊。它包含具體型別的大小和對齊。這些資訊之所以在裡面,是因為對於像 box 這樣你必須釋放記憶體的東西,這些資訊是必要的,要傳給配置器來做釋放。
[1:42:44] 所以每個 trait object 都包含 V,或者說每個 trait object 的 V table 都包含該 trait 的方法,加上 drop,加上大小,加上對齊。通常你不需要想這些,但既然我們談到這個話題,知道一下也好。稍微換個話題,到目前為止我們真的只談了 trait objects,但還有其他不是 sized 的型別。例如,我們知道 din trait 不是 sized,但 u8 也不是 sized,而 str 也不是 sized。
[1:43:20] 這個東西會被轉換,當你把它放在參照或指標後面時,它會被轉換成一個元組,包含一個指向資料的指標和一個指向 vtable 的指標。這個東西,如果你讓它有大小或把它放在指標後面,也會變成一個寬指標,其中一個是指向資料的指標,但另一個只是一個 u-size,也就是切片(slice)的長度。而 str 也是一樣,作為指向資料的指標和一個長度的 u-size。
[1:43:57] 所以這就是為什麼,如果你試著寫一個函式 foo 接受一個 u8,編譯器會對你大叫,說型別 U8 的值的大小未知。因為 U8 這只是表示一個任意長度的 U8 列表,它是沒有大小的。因此我們不能用它作為引數來呼叫函式。就像如果你試著直接回傳一個 U8 序列一樣,對吧?如果我有一個 bar,它回傳一個 U8。
[1:44:33] 嗯,它也會抱怨。喔,呃,它甚至會讓我這樣做嗎?好了。我建構了這個型別。所以這裡它說了同樣的話。型別 U8 的值的大小無法得知,而函式的回傳型別必須有靜態已知的大小。所以這是同樣的問題。這裡也一樣,我們從沒有大小的東西變成有大小的東西的方式,就是把它放在一個可以某種程度上遮蔽「沒有大小」這個性質的型別後面,你可以用參照來做到,或者你可以用 box 來做到。
[1:45:14] 所以你也可以對這個做 box。我想我可以這樣做。太好了。所以這沒問題,因為它現在有大小了。它的大小是一個寬指標,其中一部分是資料,另一部分是長度。嗯,然後編譯器就知道當你存取,呃,這個型別時,它知道要某種程度上解構這個指標來取得長度。
[1:45:51] 嗯,跟 box 或原始指標之類的東西一樣。字串也一樣。所以這些東西有點神奇。已經有一些工作在嘗試將這個標準化。所以目前這種動態大小的型別在編譯器裡有點特殊,因為你需要知道指標是否是寬的。所以自己處理沒有大小的型別相當困難。比如說,如果你想要自己實作 box 並接受一個沒有大小的型別,這是可能的。
[1:46:27] 一旦你進入型別轉換和允許 trait 物件之類的東西,就會變得相當煩人。但最近有一個 RFC 通過了。RFC 編號 2580。它談到要加入一個泛型 API 來操作胖指標的元資料。所以這讓你可以做像是說出胖指標第二部分是什麼型別這樣的事。對吧。所以以這個情況來說,我們其實可以往下捲一點,看看一個 DIN trait 現在變成一個 pointy,其中元資料是 DIN 元資料。
[1:47:09] 而我們是 DIN 中介資料。它是一個指向 Vtable 的指標,代表所有資訊,例如型別大小、型別對齊、drop 與 place 的指標,以及該型別所有方法的指標,用於特徵的簡化。所以正是我們剛才談到的內容。同樣地,你可以想像這個 pointy 特徵會為類似 U8 切片(不含參考)的型別實作,其中中介資料會是一個 U 大小,也就是該東西的長度。
[1:47:44] 這仍然非常像新功能且屬於實驗性質。我確實建議你讀一讀這份 RFC。如果你想進一步了解,它真的很有意思。它包含像 trait alias thin 這樣的東西,也就是任何實作了 pointy 且中介資料為空的型別,這會是任何在指標中沒有關聯中介資料的東西,所以是任何屬於 thin pointer 而非 fat pointer 的東西。它基本上還提供了用於內省指標中介資料的方法,讓你可以做像實際檢視 Vtable 這樣的事。
[1:48:16] 稍早在聊天中有一些關於此的問題。這份 RFC 實際上會讓你內省那項資訊,並且關鍵地即時建構 Vtable。所以你可以有一個在編譯期未知、但在執行期建構的 Vtable。而事實上,就我所知,這已經是標準函式庫中某個地方存在的東西,也就是在非同步領域中用於 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,你可以透過提供 clone 方法、wake 方法、wake by ref 和 drop 的函式指標來建構 raw waker vtable。
[1:50:03] 所以這基本上就是一個手動建構的 Vtable,讓你透過型別而非 trait 來實現動態分派。我不會深入太多細節,我只是想把它當作標準函式庫中手動建構 Vtable 的範例來展示。從這裡開始我還有什麼想講的嗎?我想沒有了。好,我們來問問題吧,因為我已經講了一段時間了。
[1:50:38] 我以為 U8 的參照有一個起始指標和一個結束指標,而不是長度。我想它是有長度的。它沒有,這兩者基本上等價。你也許是對的,我忘了。事實上,我想知道這份參照怎麼說。是的,你看,這份 RFC 也棄用了 Trait 物件那些存在於 Nightly 的東西,因為這是替代方案。
[1:51:11] 指標型 trait、精簡中繼資料、從原始部件建構。哪裡有……的定義?喔,它其實沒有給出。對,我本來希望它會在這裡說明切片實際的關聯中繼資料型別是什麼,但我沒看到。
[1:51:42] 我想就只是長度。我們能自己建立動態大小型別嗎?算是可以。所以你可以這樣寫。這裡的 foo 現在不是固定大小的了。事實上,你可以新增更多欄位。不過你不能在這之後新增欄位。在這之後就不是固定大小的了,對吧?
[1:52:14] 所以如果我試著這樣做,它會告訴我 u8 的值大小無法在編譯期得知。只有結構體的最後一個欄位可以擁有動態大小的型別。請將欄位型別改為具有靜態已知大小。借用型別總是具有靜態已知大小。所以這要表達的是,如果它是最後一個欄位,那就回想我很久以前提出的論點,對吧?如果你在這裡中間有一個非固定大小的型別,而我問你,比如說我想查找 foo.x,而你只有一個指向 foo 的指標,當中間的型別可以有任意大小時,你要怎麼取得指向 x 的指標?
[1:52:54] 答案是你辦不到。你不知道如何取得 x 的位址,因為 t 是任意大小的。但如果它在最後,那就沒問題。你可以靜態得知 f 的偏移量、x 的偏移量和 t 的偏移量。而要讓這個型別變成固定大小,唯一需要的資訊就是最後一個欄位的長度。所以你可以建構這樣的型別。這個型別現在不是固定大小的了。但如果你有一個指向 foo 的指標,那麼該型別就會透過儲存指向 foo 的指標以及 t 的長度而變成固定大小。
[1:53:34] 所以你可以用這種方式建立自己的動態大小型別。box U8 和 vec U8 是同一回事嗎?所以這是當你有一個 U8 切片的 box,而不是在參照後面時,就是 vec U8。它們不是同一回事。所以不是。我想我們這樣做吧。
[1:54:05] 它們不一樣。它們感覺一樣,但其實不一樣。哎呀。Vec 可以增長。所以 Vec,首先,它有三個字。它是指向堆積上向量資料的指標。它是向量的長度,也是向量的容量。這樣設計是為了當你嘗試在容量範圍內推入元素時,長度就只會遞增。如果你嘗試推入超出容量的元素,那麼整個向量會重新配置、複製過去,然後再變更。
[1:54:39] 用 Box 切片 8,你做不到這件事。它永遠不會增長或縮減。你不能對它推入元素。它就只是,把它想成一個,它真的就只是一個切片。你可以把 Vec 切片轉成 Box 切片。你也可以反過來做。但它們不一樣,沒錯。dyn fn 和 fn 之間有什麼差別?
[1:55:28] 所以基本上,我可以寫一個 fn foo 來接收 dyn fn。我也可以寫一個 fn bar 來接收 fn。這兩者之間有什麼差別?它們不一樣。這必須是一個函式。它不能是閉包。原因是 fn 實際上就是一個函式指標。
[1:55:59] 就像它只是一個必須是位址的單一指標。這是一個虛擬函式表。它是一個特徵物件,這表示它既有你可以想像成這裡的虛擬函式表,裡面有指向……呼叫函式的指標,但它也有一個資料指標,對吧?因為這個的結構是它是一個寬指標,其中一部分是虛擬函式表,裡面有實際呼叫函式的指標,但另一部分是資料指標。而關鍵在於,這裡的差別是,如果我有 fn main,我可以用閉包呼叫 foo。
[1:56:41] 所以我可以傳入一個函式。這樣可以,但我不能對 bar 做同樣的事。為什麼它在抱怨?喔。對,所以我可以傳閉包給 foo,因為這個閉包捕獲了 x,對吧?
[1:57:16] 所以它不只是函式指標,它是函式指標加上閉包從其環境捕獲的資料。也就是說,當你呼叫閉包時,你也需要提供 x 的位址,因為閉包的主體需要它。而這就是透過寬指標的資料部分傳入的。對於 bar,它需要一個真正的函式指標,這表示你不能傳入閉包,因為你沒有地方可以存放資料。當我們使用 dyn fn 而非 impl fn 時,對,所以還有 baz 的 impl fn。
[1:58:03] 嗯,而且我可以用閉包呼叫 Baz。怎麼回事?它在抱怨什麼?我可以用閉包呼叫 baz,因為還記得嗎,impl fn 算是對任何實作 fn 的型別之泛型函式的語法糖。
[1:58:34] 所以我們實際上會為每一種傳入的閉包型別產生一份具體的 baz 副本。因此,你也可以輕鬆地把資料傳進去,因為它會針對每個個別閉包進行單態化。接下來的問題就變成:什麼時候該用 dinfn,什麼時候該用 implfn?基本答案是……implfn 的適用範圍更廣。比如說,你不必透過指標做間接呼叫。但你最終會為每一種傳入的閉包型別各產生一份 Baz 副本,數量可能會相當多。
[1:59:12] 另一個原因是,有時你會想改用 trait 物件,而不是把它泛型化,否則你就得把泛型型別往上傳遞。所以想像我有一個……struct 包裝器,然後在內部我想讓它包含一個函式指標。如果我讓它持有……我其實可以這樣寫,對吧?我可以這樣做,但這意味著任何想使用我這個函式庫、想持有這個包裝器的人,自己也必須對 f 泛型化,或者寫出 f 的型別名稱。
[1:59:51] 反之,如果這裡改成儲存一個 box din fn,那麼包裝器就不再是泛型的,我的呼叫端就不必去考慮並傳遞那個泛型參數。所以有時這能讓你的介面更乾淨,用起來更順手。還有一個例子是讓 trait 成為物件安全的。所以如果我有一個 trait x,裡面有一個 fn foo,如果我讓它接受 impl fn,那麼 x 就不是物件安全的。
[2:00:28] 我就沒辦法寫出一個 crocs。我想就讓它接受 self 吧。trait x 不是物件安全的,因為這是泛型的。implfn 等於是在說 f 是 fn,而這就是 f。
[2:01:01] 而這就像我們談過的,無法做成物件安全的。但另一方面,如果我把它改成 dinfn,它就可以是物件安全的,因為只有一個 foo,對吧?所以我們不會遇到需要無限多個 vtable 項目的問題,就只有一個 foo,而它本身接受一個寬指標,這樣就能適用於任何可作為物件安全的型別。所以這裡沒有明確的答案。嗯,不錯。
[2:01:49] 好,我想,我想這涵蓋了……我想談的所有內容。所以我們唯一沒談到的是連貫性。我覺得連貫性差異夠大,我們這場直播就不談了,我可能會另外開一場直播專門講它,特別是我們現在已經到兩小時的關頭了。所以我覺得這是個停下來的好時機。
[2:02:22],然後就單獨做這件事。到最後,關於我們目前談過的所有內容,有沒有什麼問題?靜態派發與動態派發的一般差異、size trait、V table、物件安全性、寬指標與胖指標,這些現在大致上都清楚了嗎?或者還有什麼我可以再講一遍,幫助你釐清、讓你明白為什麼我們要有這些東西、它們的用途是什麼、有什麼限制?我很樂意在最後回答一些問題。
[2:03:00] 未來有可能用某種類型的 vtable 來實作執行期 trait 偵測嗎?如果我正確理解你的問題,我認為不行。所以問題是:你能不能拿一個 trait 物件,或拿一個寬指標,光看它的 V table 就判斷出它實作了哪些 trait?我認為不行。部分原因是,每個 trait 物件都會產生不同的 vtable。
[2:03:37] 所以並不是 str 或 string 只有一個 vtable,對吧?string 有很多個 vtable。每個 dyn trait 的 string 都各有一個 vtable,對吧?嗯,所以不是只有一個 V table,讓你去看就能判斷它實作了哪些 trait。嗯,比如說如果你有一個 find traits,它接收一個是 dyn、某個 trait 的 S,嗯,那麼 V table 裡只會有你在這裡指定的那個 trait 上的方法。
[2:04:24] 你不會得到一個包含所提供型別上所有可能方法的 V table。所以不行,我認為你不能用這種方式動態偵測某個東西實作了哪些 trait。呼叫 dyn fn 會涉及雙重解參考嗎?一次是取 Vtable 指標,一次是取其中的實際函式指標,還是這會被最佳化掉?所以如果我呼叫一個接收 Fn 的 F 的函式,然後在這裡我做 F。
[2:05:07] 你知道嗎,這是個好問題。我認為最後會變成雙重解參考,因為你首先得經過……這不完全是雙重解參考,因為這是個寬指標,對吧?它不是指向一個由指標和 V table 組成的元組的指標,對吧?真正傳進來的是指向某個 T 的指標。
[2:05:39] 你只是不知道那個 T 是什麼,以及一個指向 T 的 FN V table 的指標。這才是這裡真正傳進來的東西。所以這最後會呼叫像是 Vtable.call of t。因此這裡有一個解參考。就像,這是指向 Vtable 的指標。
[2:06:12] 所以你確實必須對 Vtable 解引用。我想這是比較好的方式來把它型別化出來。所以你確實必須對 Vtable 解引用才能取得呼叫。我想,這其實就是這樣,對吧?你必須對 Vtable 解引用,才能找到你要呼叫的那個呼叫的位址。所以最後確實是兩次解引用,但這也不太算是指標追逐。這是真的。
[2:06:58] 好,所以有一件事稍微有點古怪,對吧?就是如果你有一個 X,它接受一個 S,比如說 dyn S ref str,那麼你可以做的一件事,這在聊天室裡有提到,有了新的指標 Vtable 動態中繼資料 RFC,你可以想像,如果 s.Vtable 等於 string as dyn asrefster.Vtable,那麼就像,s 作為參考 f s 點 data 作為參考到 string 點,我猜如果這是可變的,呃,點 push,對吧,也許你可以做這種非常奇怪又醜陋的魔法。
[2:08:02] 我會建議就別這麼做。但沒錯,你可以想像你可以這樣比較 Vtable。我不知道這是否甚至能保證編譯器會維持一個型別永遠只會恰好有一個 Vtable。而且沒錯,編譯器在這裡也做了相當多的最佳化。比如如果你做 box dyn FN,我想它可能不一定總是會做堆積配置,如果你,如果只是像逃逸分析之類的。但一般來說,如果你使用泛型,比如如果你使用實際的泛型型別參數,或 impl 區塊,抱歉,impl trait,在那些情況下,你會得到更好的最佳化,因為編譯器在編譯期就能完整洞察所有相關型別是什麼,並能根據實際的具體實作進行共同最佳化。
[2:08:52] 而一旦你透過動態派發進行間接呼叫,編譯器就會失去一些它原本會擁有、並能據以最佳化的資訊。你可以做個 dyn 的 sliceVec 的快速範例嗎?喔,可以。說 hi。所以如果你真的想這麼做,我想我們有 dyn hi,但讓我們把它改成 dyn asref stir。然後你想要像 for H 和 S。
[2:09:27] 讓我們把它改成 V。對於 S 和 V,S.asref。嗯,所以為了真正讓這個運作起來,呃,你最後必須這麼做,嗯,來讓它有大小,對吧。嗯,這樣陣列的所有元素都是相同大小,因為陣列要求如此,這樣你才能找到給定的索引。對吧。嗯,而一旦你這麼做,嗯,這個 salt 就自然運作了。
[2:09:59] 而且你也可以為內部型別放一個方塊、弧線或任何東西。不同的編譯單元可能會導致不同的 V table。聽起來大致正確。所以這有點像是軼聞,但當你編譯 Rust 程式碼時,Rust 可能會用多個獨立的執行緒來編譯一個 crate,分別編譯該 crate 的不同子集,以加快編譯速度。但因為你希望那些獨立的單元能完全並行運作,而不需要太多同步,它們可能都會遇到,比如說,一個……
[2:10:37] 字串被當作 dyn asref 使用,它們可能都會各自產生自己的 vtable,因為它們不想為了產生 vtable 而進行協調,因此即使是同一個型別、同一個 trait,你也會有多個 vtable。這就是為什麼那個不變量可能不成立的一個例子。這是個好觀點。而且沒錯,還有 any,我還沒談到。我不會實際示範它,但就是有 any 這個 trait。而 any 超級神奇。
[2:11:09] 它其實不是像 any 就只是一個 trait,裡面有一個函式會回傳型別的識別碼,那個識別碼是唯一的,由編譯器保證。所以如果你有一個對 any 的 trait 物件,你可以在它上面使用 type ID,因為它會被加進 V table,以取得該值的唯一……型別識別碼,然後你就可以用它從 dyn any 向下轉型成具體型別,因為我們知道型別識別碼是什麼。我不會太深入講 any,但 any 大量使用了我們目前談過的東西,才能夠從 dyn 一個 dim trait(只要該 trait 包含 any)轉成對實際底層型別的參照。
[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(參見 關於這些頁面)。
最後更新