TRANSCRIPCIÓN · CC BY 4.0

Crust of Rust: despacho, monomorfización y punteros gordos — Jon Gjengset

Título original en inglés: Crust of Rust: Dispatch and Fat Pointers

Jon Gjengset · Publicado el · 2 h 13 min · Audio original en inglés · subtítulos en español · Licencia: CC BY 4.0 · Fuente: ver en YouTube

Esta ficha ofrece el título y el contexto en español junto con la transcripción original íntegra en inglés con marcas de tiempo. Pulsa el botón superior para abrir la vista bilingüe español-inglés sincronizada en el lector.

Resumen generado por IA

Esta transmisión de Rust cubre un conjunto de temas semi-relacionados—traits, despacho estático y dinámico, el trait Sized, punteros anchos o gordos, vtables y coherencia—con el objetivo de explicar cómo encajan entre sí sin profundizar demasiado en ningún tema, posiblemente omitiendo algunos detalles para ajustarse al tiempo y dejando las inmersiones profundas para más adelante. Deconstruye la sección del Rust Book sobre el rendimiento de los genéricos, particularmente la monomorfización: convertir código genérico en código específico rellenando los tipos concretos en tiempo de compilación, como cuando un strlen genérico que acepta cualquier cosa que implemente AsRef<str> se llama con un &'static str y un String y el compilador genera dos copias, o cuando un HashMap genérico obtiene copias de su struct y métodos por cada tipo usado, generadas bajo demanda. Esto hace que distribuir código Rust como biblioteca, como bibliotecas enlazadas dinámicamente, sea algo difícil ya que se necesita el código fuente para generar instancias para los tipos del consumidor; los beneficios incluyen código potencialmente mucho más eficiente mediante inlining y optimización, mientras que las desventajas incluyen binarios más grandes, una eficiencia de caché de instrucciones ligeramente peor y cierto coste de compilación. El despacho estático se explica mediante un trait personalizado implementado para str, donde el tipo concreto se conoce en tiempo de compilación, por lo que la llamada se convierte en una llamada en ensamblador a una ubicación conocida; el despacho dinámico es la alternativa cuando no se quieren múltiples copias, como en un vector de cosas que implementan el trait. Luego la charla explica por qué no se puede crear un vector de tipos distintos, el ejemplo de dibujo de GUI, los objetos trait indicados por dyn, el trait marcador Sized requerido implícitamente por cada trait bound, el borrado de tipos, los punteros gordos que contienen un puntero a datos y un puntero a vtable, las reglas de seguridad de objetos y por qué traits como Clone y Extend no pueden convertirse en objetos trait. Un segmento posterior cubre los tipos de tamaño dinámico, los objetos trait y el despacho: un trait DIN se convierte en un trait pointy cuyos metadatos son metadatos DIN, un puntero a una vtable que contiene el tamaño del tipo, la alineación, los punteros drop y place, y los punteros a métodos; el trait pointy podría implementarse de manera similar para un slice de U8 sin la referencia, con una longitud de tamaño U como metadatos. La característica aún es nueva y experimental, y el ponente recomienda leer el RFC, que incluye un alias de trait thin para cualquier tipo que implemente pointy con metadatos vacíos, proporciona métodos para introspeccionar los metadatos del puntero y, crucialmente, permite construir vtables sobre la marcha en tiempo de ejecución, como ya hace la biblioteca estándar para los wakers en async. Contrasta fn, dyn fn e impl fn, señala la incertidumbre sobre cómo una referencia a un slice de U8 almacena su longitud, y explica que solo el último campo de un struct puede tener un tipo de tamaño dinámico. La petición de un oyente de un slice Vec de dyns lleva a los objetos trait, las vtables y el trait Any: los elementos del array deben hacerse del mismo tamaño, y diferentes unidades de compilación pueden generar vtables diferentes para el mismo tipo y trait. Any se describe como un trait con una función que devuelve un identificador de tipo único del compilador, añadido a la vtable para permitir el downcasting. La sesión termina a las 2 horas y 15 minutos aproximadamente con agradecimientos.

Resumen traducido automáticamente con IA a partir de la transcripción. Comprueba los fragmentos enlazados con el vídeo original.

Resúmenes por capítulo con marcas de tiempo

Traits, despacho y monomorfización

Alcance de la transmisión: temas de traits y despacho

  • [0:28] La transmisión cubre un conjunto semi-relacionado de temas en torno a traits, despacho dinámico y estático, el trait Sized, punteros anchos o gordos, vtables y coherencia.
  • [0:52] Estos temas están conectados entre sí, algunos más que otros, y el objetivo es explicar cómo funcionan y encajan sin profundizar demasiado en ningún tema.
  • [1:13] La mayoría de los temas se cubrirán con un detalle práctico, con posibles inmersiones profundas en transmisiones posteriores, por lo que algunos detalles pueden omitirse para ajustarse al tiempo.

Rust Book sobre rendimiento de genéricos

  • [1:35] El Rust Book tiene un capítulo sobre tipos genéricos, traits y tiempos de vida, que incluye una subsección sobre el rendimiento del código que usa genéricos.
  • [1:59] La transmisión pretende deconstruir la aparente magia de esa sección, particularmente la idea de monomorfización.
  • [2:07] La monomorfización se describe como el proceso de convertir código genérico en código específico rellenando los tipos concretos usados al compilar.

Ejemplo de strlen genérico

  • [3:17] Una función genérica strlen acepta cualquier cosa que implemente AsRef<str> y devuelve un usize mediante as_ref().len().
  • [3:46] La forma equivalente es una función genérica sobre S donde S implementa AsRef<str>, y ambas son funciones genéricas que aceptan cualquier tipo convertible a una referencia a str.
  • [4:36] Una función foo llama a strlen con "hello world" (un &'static str) y con String::from("hello world") (un String), mostrando que las dos llamadas pasan tipos diferentes.
  • [5:30] String implementa AsRef<str> porque una referencia a un String puede producir trivialmente una referencia a un str, ya que la representación interna de un String es un str.

Monomorfización de llamadas genéricas

  • [5:44] Los genéricos son útiles porque permiten llamar a una función dada de manera más flexible o ergonómica.
  • [5:56] Entre bastidores, el compilador genera dos copias de la función, una por cada tipo usado, que es lo que el Rust Book llama monomorfización.
  • [6:10] En tiempo de compilación, esto genera una strlen para &str que toma un str y llama a str::len, y una strlen para String que toma un String y hace lo mismo.
  • [6:39] Una definición genérica es convertida por el compilador en múltiples implementaciones no genéricas, lo cual es clave para cómo funcionan los genéricos en Rust.

Monomorfización en los genéricos de Rust

Generación de código bajo demanda para tipos genéricos

  • [6:54] La monomorfización se aplica no solo a funciones, sino también a tipos.
  • [6:59] Un HashMap genérico recibe una copia completa de la estructura y de todos sus métodos por cada tipo con el que se usa.
  • [7:13] No se generan copias para tipos que nunca se invocaron; la generación es bajo demanda en tiempo de compilación, no para todos los tipos posibles.
  • [7:34] Una instancia concreta del tipo HashMap solo se genera si esa combinación de tipos aparece realmente en algún lugar del código.

Distribución binaria y la necesidad del código fuente

  • [7:46] Esta es una de las razones por las que resulta algo difícil compilar código Rust y distribuir un binario utilizable como biblioteca, como las bibliotecas de enlace dinámico.
  • [8:11] El contrato de Rust es generar copias distintas de la función para cada tipo, pero un consumidor puede instanciarla con un tipo no definido donde reside la función de origen.
  • [8:26] Por lo tanto, se necesita el código fuente para generar todas esas instancias.

Ganancias de rendimiento gracias al código concreto

  • [8:31] La monomorfización es excelente porque puede producir código potencialmente mucho más eficiente.
  • [8:54] Con HashMap, cada tipo de clave concreto recibe su propia copia, de modo que el compilador puede insertar en línea la función de hash para cada tipo de clave.
  • [9:26] La versión de HashMap con claves de tipo string coloca el código de hash de strings directamente en el código de HashMap y puede optimizar según que el tipo sea un string.
  • [9:41] Para una clave numérica, el compilador podría omitir por completo el hash una vez monomorfizados los genéricos, aunque el ponente señala que puede que eso no sea realmente cierto.
  • [9:54] El compilador llega a ver el código concreto y explícito para los tipos particulares usados, lo que le permite optimizar mucho mejor.

Binarios más grandes y generación parcial de métodos

  • [10:28] Una desventaja de la monomorfización es que el binario acaba siendo más grande porque se genera una copia del tipo o de la función por cada tipo con el que se usa.
  • [10:45] El crecimiento no es tan grave como multiplicar por el número de tipos, porque solo se generan los métodos realmente llamados para una combinación de tipos dada, lo que amortigua un poco el coste.
  • [11:14] Sigue siendo cierto que la monomorfización conduce a más código en el binario final.

Eficiencia de la caché de instrucciones y coste de compilación

  • [11:20] Un efecto secundario es una eficiencia de la caché de instrucciones ligeramente peor: en lugar del código máquina de una función que puede permanecer en caché, hay dos funciones separadas en regiones de memoria distintas que deben almacenarse en caché por separado.
  • [12:07] Generar estas copias también le cuesta un poco al compilador, pero normalmente no demasiado, salvo que se instancien una cantidad muy grande de tipos.
  • [12:25] El ponente dice que los binarios de Rust más grandes que los de C son ligeramente diferentes, ya que los binarios de Rust compilan estáticamente más cosas.

Tamaño de los binarios de Rust, monomorfización y genéricos

Causas de los binarios de Rust más grandes

  • [12:38] La monomorfización es parte de la razón por la que los binarios son más grandes, y puede que se compile más código de la biblioteca estándar.
  • [12:48] Otro factor importante es que Rust a menudo incluye símbolos de depuración, así que puede valer la pena intentar eliminar los símbolos del binario.

Monomorfización e inlining de funciones genéricas

  • [13:07] La monomorfización ayuda porque una función genérica como bool_then puede generar una copia con el código del closure pasado directamente inline.
  • [14:18] El inlining no está garantizado: como la función se monomorfiza a un tipo particular, el compilador conoce el tipo y puede elegir hacer inlining y optimizar si lo desea.

Uso de la biblioteca estándar y coste de duplicación de código

  • [14:42] Solo las partes de la biblioteca estándar que realmente se usan acaban en el binario, pero el uso intensivo de los genéricos de la biblioteca estándar aumenta su tamaño.
  • [15:00] Duplicar métodos no cuesta básicamente nada en tamaño, pero compilar muchas copias de una función a código máquina ralentiza la compilación.

Referencias y límites del enlace dinámico

  • [15:18] Una función similar a strlen podría tomar una cadena por valor o una referencia, y tomar una referencia es una de las razones por las que &str es agradable.
  • [15:34] Las bibliotecas dinámicas no manejan genéricos, lo que dificulta el enlace dinámico o la distribución de binarios de bibliotecas Rust; las funciones externas en una biblioteca enlazada dinámicamente al estilo C no pueden ser genéricas.

Despacho estático y monomorfización en Rust

Definición de un trait Hello personalizado

  • [16:40] El ponente define un trait personalizado, llamado Hello o un hola noruego, con un único método que no devuelve nada y solo dice hola en noruego.
  • [17:10] El trait está implementado para str, y el método imprime una línea usando self.

Resolución de métodos en una referencia str concreta

  • [17:46] Al generar código para una llamada sobre una referencia a str, el compilador determina el tipo y comprueba qué métodos están disponibles en ese tipo de referencia.
  • [18:06] No encuentra ningún método llamado hi en el tipo de referencia, luego busca en los traits en ámbito y encuentra el método hi implementado para el tipo del receptor, así que llama a ese.

Función genérica y monomorfización

  • [18:21] En una versión genérica que toma algo que implementa hi, el compilador debe llamar al método sin conocer el tipo de H.
  • [18:47] La monomorfización genera una versión concreta como bar_str con H ligado a str, por lo que el tipo concreto es conocido.

Despacho estático en tiempo de compilación

  • [19:10] Esto es despacho estático: en tiempo de compilación el compilador conoce el tipo real, así que sabe qué método se está llamando.
  • [19:22] La llamada se convierte en una llamada en ensamblador a una función en una ubicación de memoria conocida, lo que hace trivial la compilación una vez generado el método especializado.

Despacho dinámico como alternativa a la monomorfización

Despacho estático y azúcar de impl Trait

  • [19:50] El ponente señala que este método es realmente el mismo que el otro, y ambos hacen trivial averiguar dónde reside el método high.
  • [20:27] `impl Trait` es solo azúcar sintáctico para genéricos, equivalente a la forma genérica `H: High`.

Motivación: evitar múltiples copias

  • [20:50] La alternativa es necesaria cuando no quieres monomorfización, es decir, no quieres que se generen múltiples copias.
  • [21:03] Otra motivación es querer un vector de cosas que implementan High y llamar a `h.high` en cada elemento.

Slices de un único tipo concreto

  • [21:29] Iterar sobre un vector y llamar a `h.high` está bien si todos los elementos son del mismo tipo.
  • [21:51] Una función `bar` que toma un slice de cosas que implementan High funciona y compila bien cuando se llama con un único tipo concreto.
  • [22:27] Convertir cada elemento en cadenas también funciona bien, aunque el ponente señala que no habían implementado esto para string.

Necesidad de colecciones heterogéneas

  • [22:58] No puedes crear un vector de cosas que sean de tipos diferentes en primer lugar.
  • [23:08] En este caso el tipo concreto no importa; lo único que importa es que los elementos implementen el trait High.
  • [23:19] El ponente sostiene que deberías poder crear un vector de cosas con este comportamiento sin preocuparte por el tipo concreto.

Despacho dinámico y objetos trait

Tratar diferentes tipos concretos como un solo tipo

  • [24:00] El libro tiene un capítulo decente sobre tratar cosas de diferentes tipos concretos como el mismo tipo.
  • [24:10] Un ejemplo de GUI: muchas cosas implementan el rasgo draw, como botones, imágenes y cuadros de texto, y una función draw solo necesita un iterador de cosas dibujables.
  • [24:39] Esto se parece a querer tomar una porción de cosas sobre las que se puede llamar a un método como high.

Por qué falla un único parámetro de tipo genérico

  • [24:48] Lo que se necesita se conoce como objeto de rasgo, indicado por la palabra clave dyn.
  • [25:05] Escribir el atajo impl muestra que Bar es genérico sobre un tipo, que debe ser una referencia a str o un String, no ambos.
  • [25:28] Con una porción o un iterador no hay dónde poner un segundo parámetro de tipo, ya que el iterador tiene elementos de un solo tipo.

Errores del compilador por dyn y valores sin tamaño definido

  • [25:55] Escribir el tipo de rasgo desnudo produce un error del compilador que indica que los objetos de rasgo sin un dyn explícito están obsoletos, así que se añade dyn.
  • [26:16] El siguiente error dice que el tamaño para valores de tipo dyn high no se puede conocer en tiempo de compilación, y que el rasgo Sized no está implementado para dyn high.
  • [26:29] Los elementos de porciones y arreglos deben tener un tipo con tamaño definido, un error que el ponente planea explicar junto con lo que significa Sized y cómo se relaciona con el despacho dinámico y los objetos de rasgo.

El borrado de tipos como objetivo previsto

  • [27:14] El objetivo puede concebirse como borrado de tipos: tomar una colección de cosas preocupándose solo de que implementen el rasgo, es decir, una noción abstracta del rasgo.
  • [27:35] El desafío del compilador es precisamente este caso, que el ponente se detiene a comprobar que tenga sentido.

Por qué el rasgo Sized de Rust importa para los tipos genéricos

Sized como rasgo marcador con límites implícitos

  • [27:54] El rasgo Sized no tiene métodos y es un rasgo marcador definido en el módulo marker, descrito como tipos con un tamaño constante conocido en tiempo de compilación.
  • [28:07] La mayoría de los tipos, incluidos structs como Foo y la mayoría de los tipos de la biblioteca estándar, tienen tamaño definido, y muy pocos tipos no lo tienen.
  • [28:21] Cada límite de rasgo, incluso un simple Foo<T>, lleva un límite implícito que requiere que el tipo tenga tamaño definido.

El compilador necesita tamaños de argumento conocidos para la generación de código

  • [29:05] Un strlen genérico sobre S que implementa *str toma S y devuelve usize mediante la longitud de la referencia.
  • [29:34] El argumento debe ocupar espacio en la pila o pasarse en un registro, así que el compilador debe saber cuán grande es para asignar espacio en el ensamblado generado.
  • [30:23] Para la implementación de String, el compilador sabe que el argumento son tres palabras (longitud, tamaño de asignación y puntero al heap), por lo que el ensamblador puede generarse trivialmente.
  • [31:02] De manera similar, ser genérico sobre el tipo de retorno requeriría saber cuánto espacio de pila asignarle.

Por qué dyn Trait no tiene tamaño definido y rompe las porciones

  • [31:44] dyn Hi significa cualquier cosa que implemente Hi sin un valor concreto, ya que el slice puede contener String, str u otros implementadores de diferentes tamaños.
  • [32:03] String son dos números y un puntero, str es un número y un puntero, y un hipotético Foo podría ser de un gigabyte, por lo que el slice no tiene un tamaño de elemento único.
  • [32:28] Un slice es memoria contigua donde cada fragmento es del mismo tamaño, así que si los tamaños de los elementos son desconocidos, no se puede garantizar elementos del mismo tamaño.
  • [32:52] La aritmética de punteros para el cuarto elemento (inicio más tres veces el tamaño del elemento) no puede generarse si los elementos difieren en tamaño, por lo que los elementos de slices y arrays deben tener un tipo sized.

Solucionar el problema de la colección sin tamaño definido

  • [33:24] El ponente quiere conservar la capacidad de hablar de cosas que implementan un trait como una colección, ya que sería una locura que Rust careciera de ello.
  • [33:45] Un strlen2 que toma dyn AsRef<str> tiene el mismo problema que el ejemplo del slice.

El trait Sized de Rust y los tipos unsized

Error del compilador para argumentos unsized

  • [33:57] Compilar el ejemplo produce el error de que el tamaño de los valores de tipo dyn AsRef<str> no puede conocerse en tiempo de compilación, y Sized no está implementado para dyn AsRef<str>.
  • [34:17] El compilador requiere que los argumentos de función tengan un tamaño conocido estáticamente, mientras que los tipos prestados siempre tienen un tamaño conocido.
  • [34:26] El compilador debe conocer el tamaño del tipo de un argumento para generar el código de llamada a la función, lo que hace que los tipos sized sean un requisito fundamental.

Implementación automática de Sized

  • [34:59] Sized se implementa automáticamente para cualquier tipo que pueda implementarlo, así que un struct sin campos, o uno que contenga un String o un bool, es sized.
  • [35:27] Un struct genérico foo<T> sigue siendo sized porque cada trait bound conlleva un requisito implícito T: Sized, por lo que todos los campos son sized.
  • [35:50] Nunca implementas Sized tú mismo; solo se usa como auto trait.

Por qué el compilador necesita tamaños conocidos

  • [36:09] El problema no es el tamaño de la pila ni si un valor podría no caber en ella.
  • [36:18] En la capa de código máquina o ensamblador, llamar a una función requiere saber cuánto espacio asignar para sus variables de pila, argumentos y valor de retorno.
  • [36:49] Aunque hay formas astutas de hacerlo, el compilador debe conocer el tamaño de estas cosas para generar código eficiente.

Ejemplos de tipos unsized

  • [37:19] Un trait desnudo usado como tipo de parámetro, como tomar un Hi, no es sized porque muchos implementadores pueden tener tamaños diferentes.
  • [37:37] Usar impl aquí es un atajo para un parámetro genérico, así que es sized porque existe una copia de la función para cada tipo concreto mediante despacho estático y monomorfización.
  • [38:08] Tomar el trait en sí, equivalente a escribir dyn Hi, no funciona porque no es sized.
  • [38:29] Un struct que contiene un str no es sized porque la cadena en sí, no el puntero a ella, puede ser de cualquier tamaño; un slice sin una referencia también es unsized porque su número de elementos es desconocido.
  • [39:01] Cualquier cosa que a su vez contenga estos tipos unsized tampoco es sized.

Resolver el problema de monomorfización de Sterling 2

Método no monomorfizado propuesto para Sterling 2

  • [39:38] El hablante pregunta cómo se puede resolver la situación.
  • [39:40] El objetivo es poder tomar una variante para Sterling 2, tentativamente llamada "Sterling Din".
  • [39:49] Quieren un método como este que no se monomorfice.

Indirección para tipos de trait sin tamaño

Hacer que los tipos sin tamaño tengan tamaño mediante punteros

  • [39:58] El truco consiste en hacer que el tipo siempre tenga tamaño indirectándolo a través de un tipo que en sí mismo tiene tamaño para cualquier tipo interno.
  • [40:17] Una referencia siempre tiene el mismo tamaño, solo el tamaño de un puntero, o en algunos casos dos punteros.
  • [40:29] El compilador siempre sabe cuán grande es una referencia, sin importar qué tipo siga, porque es solo un puntero.
  • [40:43] Una box también es solo un puntero al heap, así que una vez que se usa la indirección, el tamaño del argumento es conocido.

Usar un trait sin monomorfizar

  • [40:54] Para tomar un trait en sí mismo sin monomorfizar, lo colocas detrás de algún tipo de puntero como una referencia, una box o un arc.
  • [41:28] La definición de Box usa un signo de interrogación, lo que significa que T no tiene que tener tamaño, optando por no usar la restricción automática de que todo debe tener tamaño.
  • [41:50] Por eso puedes crear una box de algo que en sí mismo no tiene tamaño.

Asignación en el heap y tipos concretos

  • [42:00] Cuando creas la box inicialmente, haces una asignación del tamaño de lo que sea que vayas a poner dentro de la box.
  • [42:48] Crear la box requiere darle algo con un tipo concreto, y en ese momento asigna espacio en el heap para ese tipo.
  • [42:57] La box sigue siendo de un tamaño conocido porque es solo el puntero, aunque la cosa a la que apunta pueda tener un tamaño arbitrario.
  • [43:13] El argumento real pasado a la función sí tiene un tamaño, así que se puede generar el código relevante.

Box frente a referencias

  • [43:57] Poner Box<dyn AsteroidStir> directamente en x también está bien, pero a Box::new todavía se le tuvo que dar un tipo concreto y con tamaño.
  • [44:23] No hay una regla fija para elegir box sobre referencias; en general, la ventaja de box es que es estática y sigue funcionando después de que el marco de pila del llamador desaparece.
  • [44:44] También puedes dar a la función una referencia a algo en la pila, pasando por una indirección de puntero y pasándola a algo que toma una referencia.
  • [45:41] El doble asterisco es necesario porque box también tiene un método asterisco.

TraitObjects y borrado de tipos en Rust

Definición de TraitObject

  • [46:17] Lo que se construyó se conoce como TraitObject, un objeto cuya única propiedad es que representa un trait.
  • [46:28] Los TraitObjects solo se comportan como algún trait subyacente, independientemente de cuál sea el tipo envolvente.
  • [46:44] Box es un tipo puntero.

Conversión de vuelta al tipo concreto

  • [46:49] Convertir un objeto trait de vuelta a su tipo concreto original generalmente no es posible, aunque técnicamente a veces sí mediante transmutaciones inseguras o el trait any.
  • [47:03] Convertir un valor en un objeto trait es esencialmente borrado de tipos: el conocimiento de qué tipo solía ser se borra.
  • [47:26] La magia de unsafe y del trait any generalmente debe ignorarse.

Solo los métodos del trait permanecen utilizables

  • [47:29] Tras la conversión, solo se conserva la capacidad de usar el trait, y todo otro conocimiento del tipo concreto se borra.
  • [47:39] Sobre un ASRF boxeado, lo único que puedes hacer es llamar a ASRF sobre él, nada más.

Despacho dinámico y mecánica de vtable

Generación de código en tiempo de compilación para llamadas genéricas

  • [48:09] Cuando el compilador genera código máquina para una función, eventualmente debe producir ensamblador que pueda convertirse en código máquina ejecutable.
  • [49:29] En el caso genérico, el compilador obtiene una copia del código para cada tipo concreto, por lo que la llamada se convierte en un salto directo a una ubicación de memoria conocida en el binario.
  • [50:05] Para una implementación concreta, el compilador sabe estáticamente en tiempo de compilación a dónde ir, lo que hace trivial la generación de código.

Objetos trait y el tipo concreto desconocido

  • [48:51] Una función como sayHi recibe un objeto trait para el trait Hi, que en realidad es solo un puntero, por lo que el compilador no sabe qué tipo es S.
  • [50:14] En el caso dinámico, el compilador no sabe si el valor es un str o un String, por lo que no puede decidir qué dirección generar.

Tablas de despacho virtual

  • [50:29] Esta situación es donde entran en juego el despacho dinámico y las v tables, o tablas de despacho virtual.

Objetos trait y tipos de tamaño dinámico

Información de tipo adicional en punteros a objetos trait

  • [50:38] Construir un objeto trait significa que la referencia o caja no ocupa solo un puntero; lleva información adicional sobre el tipo apuntado.

Referencia de Rust sobre tipos de tamaño dinámico

  • [51:24] La referencia de Rust indica que la mayoría de los tipos tienen un tamaño fijo conocido en tiempo de compilación e implementan el trait Sized.
  • [51:33] Un tipo cuyo tamaño solo se conoce en tiempo de ejecución se denomina tipo de tamaño dinámico o, informalmente, tipo sin tamaño.
  • [51:40] Los slices y los objetos trait son dos ejemplos de tipos de tamaño dinámico.

Ejemplo de determinación de tipo en tiempo de ejecución

  • [51:45] El tamaño solo se conoce en tiempo de ejecución porque en tiempo de compilación se desconoce qué tipo concreto se usará.
  • [51:58] En un ejemplo donde un valor leído del usuario determina si say_hi recibe un número o una cadena, el tipo real solo se determina en tiempo de ejecución mediante una entrada impredecible.

Tamaño del puntero para tipos de tamaño dinámico

  • [52:59] Los tipos de puntero a tipos de tamaño dinámico tienen tamaño, pero son el doble de grandes que los punteros a tipos con tamaño.

Objetos trait y vtables en Rust

Estructura de una referencia a un objeto trait

  • [53:09] Los punteros a objetos trait también almacenan un puntero a una V table.
  • [53:23] Una referencia a un objeto trait como dyn Hi almacena un puntero al tipo concreto que lo implementa y un puntero a la V table del trait referenciado.

Qué contiene una V table

  • [53:52] Una tabla V, o tabla de despacho virtual, es una estructura de datos que contiene punteros a cada uno de los métodos del trait para el tipo.
  • [54:10] Para un dyn Hi, la tabla V puede concebirse como una estructura Hi V table con un miembro, hi, un puntero a una Fn que toma un puntero a lo que sea que sea T.
  • [54:47] Se construye una tabla V diferente para cada tipo concreto convertido en un objeto trait.

Construcción de la V table durante la conversión

  • [54:57] Convertir un str en un dyn Hi produce un puntero al str más una Hi Vtable cuyo hi es str as hi.
  • [55:38] Durante la conversión, el compilador construye la Vtable y almacena su dirección dentro de la referencia.
  • [55:59] Hay una Vtable de este tipo para cada tipo que se convierte en un TraitObject.

Código de despacho generado y vtables por tipo

  • [56:10] El código generado es como s.VTable.Hi(s.Pointer).
  • [56:25] Si se pasara una cadena en su lugar, s.Vtable sería un puntero diferente, que apuntaría a string as hi en la línea 12 en lugar de str as hi en la línea 6.
  • [57:07] El código generado funciona independientemente del tipo que se pase porque indiriza a través de la tabla V y cada tipo tiene su propia tabla V distinta.

Vtables de Rust y diseño de objetos trait

Construcción de Vtables y punteros gordos

  • [57:45] Las Vtables se construyen estáticamente en tiempo de compilación en lugar de asignarse dinámicamente.
  • [58:01] Un objeto trait es un puntero gordo o ancho porque contiene dos punteros, no uno.
  • [58:16] El segundo puntero generalmente se conoce estáticamente porque está determinado por la construcción original del objeto trait, aunque técnicamente es posible construir una vtable manualmente sobre la marcha.

Representación de segmentos de cadena en objetos trait

  • [58:51] La referencia también contiene la longitud del segmento de cadena.
  • [59:06] El puntero apunta a la referencia str, que a su vez contiene la longitud, en lugar de a la cadena real.

Contenido de Vtables y depuración

  • [59:23] El ponente no conoce una forma de hacer que el compilador imprima su estructura vtable.
  • [59:33] La vtable tiene un miembro por cada método del trait correspondiente, donde el valor de cada miembro es un puntero a la implementación de ese método para el tipo concreto.

Identidad y deduplicación de Vtables

  • [1:00:12] No se construye una nueva vtable cada vez que se crea una instancia; la vtable generalmente se construye estáticamente para el tipo.
  • [1:00:32] Las vtables idénticas no se deduplican, y las implementaciones de un trait para dos tipos diferentes están garantizadas como distintas incluso si contienen el mismo código, por lo que tienen direcciones diferentes.

Box y ancho de puntero para objetos trait

  • [1:01:09] Un Box<dyn Trait> no es un puntero delgado a un puntero ancho; el box en sí es un puntero ancho.
  • [1:01:26] Box no es especial: internamente contiene una referencia dyn, y el compilador de Rust sabe que las referencias y punteros a objetos trait tienen ancho 2, por lo que Box<dyn Trait> es en sí mismo ancho sin indirección adicional.

Objetos trait con múltiples traits y límites de vtable

Por qué falla combinar dos traits

  • [1:04:12] Para que un objeto trait que combine Hi y AsRef funcione, el compilador necesitaría saber dónde están tanto el método hi como el método asref, pero esos viven en dos vtables diferentes.
  • [1:04:29] Esto requeriría no un puntero de ancho dos sino un puntero de ancho tres: un puntero a los datos, un puntero a la vtable de Hi y un puntero a la vtable de AsRef.
  • [1:04:44] Tal diseño no es intrínsecamente imposible, pero cada trait añadido seguiría aumentando el tamaño de la referencia, lo que probablemente no era lo que se pretendía.

Vtable combinada generada por el compilador y la solución alternativa con supertrait

  • [1:04:59] En teoría el compilador podría generar una vtable para la combinación y pasarla, pero el compilador de Rust actualmente no hace esto y el ponente no conoce ninguna propuesta para hacerlo.
  • [1:05:11] Una solución alternativa es declarar un trait como HiAsRef que requiera que el tipo sea tanto Hi como AsRefStr sin métodos propios, dando una única vtable más grande que contenga los métodos de ambos traits.
  • [1:05:52] Parte de la razón por la que esto no se ha incorporado a Rust en sí es que puedes optar por ello tú mismo, y no convertir automáticamente el signo más en una vtable más grande indica al desarrollador que esto podría no haber sido lo que pretendía.

Error del compilador y sugerencia para múltiples traits

  • [1:06:45] Escribir Hi + AsRefStr produce el error de que solo los auto traits pueden usarse como traits adicionales en un objeto trait, ya que ni Hi ni AsRefStr son auto traits.
  • [1:07:14] El compilador sugiere crear un nuevo trait con todos estos como supertraits y usar ese trait aquí en su lugar, y señala que los auto traits como Send y Sync están bien.

Traits marcadores y traits adicionales sin métodos

  • [1:07:27] Para traits marcadores como Send, que no tienen métodos, está bien que la vtable esté vacía, por lo que no es necesario almacenar ninguna parte adicional de la vtable.
  • [1:07:49] El ponente no cree que un trait definido por el usuario pueda usarse de esta manera, aunque ha habido una propuesta para una anotación marcadora que declare que un trait nunca tiene métodos, la cual actualmente no existe.

Objetos trait y tipos asociados

El tipo asociado rompe la compilación del objeto trait

  • [1:08:51] Añadir un tipo asociado llamado name al trait high, incluso si no se usa, hace que el código deje de compilar.
  • [1:09:28] El compilador informa que el valor del tipo asociado name del trait high debe especificarse donde se toma un dyn high.
  • [1:09:39] No puedes aceptar ningún high independientemente de su tipo asociado, porque esa información de tipo no puede capturarse en la vtable.

Especificar el tipo asociado para restaurar la compilación

  • [1:09:50] Un tipo asociado no tiene dirección en el binario, así que no hay nada que pueda colocarse en la vtable, por lo que no funciona directamente con un objeto trait.
  • [1:10:01] La solución es tomar un high donde name sea un tipo especificado, aplicando la misma restricción en el otro lugar.
  • [1:10:16] Esto funciona porque ahora hay una vtable específicamente para cualquier cosa que implemente high con ese tipo asociado como name.

Seguridad de objetos trait y exclusión de métodos de la vtable

Por qué las funciones asociadas sin self rompen la seguridad de objetos

  • [1:11:20] El compilador informa que el trait no puede convertirse en un objeto, lo que significa que no es seguro para objetos y no puede convertirse en un objeto trait.
  • [1:11:34] Para que un trait sea seguro para objetos, debe permitir construir una vtable para que las llamadas puedan resolverse dinámicamente.
  • [1:11:44] El error indica específicamente que el trait no puede convertirse en un objeto porque la función asociada weird no tiene parámetro self.
  • [1:12:17] Llamar a s.weird no es posible porque weird no toma self ni un puntero, y no existe ninguna instancia válida a la que apuntar.
  • [1:12:36] Llamarlo como Hi::weird es ambiguo porque nada especifica qué implementación usar, incluso si existe una predeterminada.
  • [1:13:14] El método no puede estar en la vtable porque no hay self, así que no está asociado con ninguna instancia de ningún tipo.

Excluir un método de la vtable con where Self: Sized

  • [1:14:21] Añadir una restricción where Self: Sized a weird requiere que el tipo implementador tenga tamaño definido, y traits como dyn Hi no tienen tamaño definido a menos que estén detrás de un puntero.
  • [1:14:43] Esto efectivamente excluye la función de la vtable y, de forma crucial, hace que no sea invocable a través de un objeto trait.
  • [1:15:06] Con esta restricción el código compila y todavía se puede crear un objeto trait y llamar a Hi.
  • [1:15:30] Llamar a weird en un objeto trait entonces falla porque el método tiene un requisito de tamaño.
  • [1:15:38] Esta es la forma de excluir cualquier función dada de la inclusión para que el trait siga siendo seguro para objetos.

Prohibir los objetos trait para todo el trait

  • [1:15:50] Añadir where Self: Sized a todo el trait prohíbe usar ese trait como objeto trait por completo.
  • [1:16:07] Esto es raro en la práctica; normalmente un trait simplemente no es seguro para objetos debido a sus métodos.
  • [1:16:22] A veces se hace por compatibilidad hacia atrás, añadiéndolo de forma proactiva por si más adelante se añaden métodos no seguros para objetos.

Pregunta del público sobre tipos asociados y despacho estático

  • [1:16:50] El ponente pregunta si el problema del tipo asociado también ocurre con el despacho estático.

Objetos trait de Rust, despacho estático y tipos asociados

Despacho estático y monomorfización

  • [1:16:54] Con el despacho estático, la monomorfización significa que se conoce el tipo concreto de cada implementación de función.

Método estático hipotético en objetos trait

  • [1:17:06] Una sintaxis como `s::weird` podría ser posible, con `weird` incluido en la vtable pero no llamado con un argumento self.
  • [1:17:41] Al hablante le parece extraño: si de todos modos se requiere una instancia del tipo para llamarlo, ¿por qué no simplemente tomar self?
  • [1:17:53] El ejemplo tradicional es un método como `new`, donde si ya tienes una instancia no necesitarías llamarlo, así que simplemente tomaría self.
  • [1:18:11] El hablante está de acuerdo en que algo así quizás podría ser posible, pero en la práctica no suele ser muy útil, por lo que no ha sido una prioridad; podría haber una razón más profunda, pero el hablante no está seguro.

`where Self: Sized` y DST concretos

  • [1:18:47] Para un trait con `where Self: Sized`, el hablante cree que aún puedes implementarlo para algo como `Box<dyn ...>`.
  • [1:19:11] Tal trait ya no puede ser un objeto trait, pero la implementación debería seguir siendo posible.
  • [1:19:24] Como es un box, se necesita una doble referencia, y esto está bien ya que el tipo boxeado no tiene tamaño dinámico; envolverlo detrás de un puntero le da un tamaño, así que `Self: Sized` en el trait no lo impide.
  • [1:20:46] Si la pregunta se refería a tipos como `str` o `u8`, no, no puedes hacer eso: Self tiene que tener tamaño cuando tienes `where Self: Sized`.

Borrado de tipos y tipos asociados en vtables

  • [1:19:53] La restricción del tipo asociado se siente extraña porque solo existe un tipo asociado por tipo concreto, así que la vtable debería saber cuál es.
  • [1:20:07] El problema es que el tipo está borrado: todo lo que queda es la vtable, así que no puedes saber por la vtable cuál era el tipo concreto.
  • [1:20:18] El trait `any` es una excepción, con un método que devuelve un descriptor del tipo concreto que solía ser, así que hay algunas formas de sortear esto.
  • [1:20:35] Los objetos trait están borrados de tipo, así que no conservas información sobre el tipo que solía ser.

fromIterator y collect en la biblioteca estándar

El trait fromIterator y collect

  • [1:21:02] El hablante señala que los métodos no pueden ser genéricos y recurre al trait fromIterator de la biblioteca estándar en lugar de continuar con el trait high personalizado.
  • [1:21:16] El trait fromIterator está implementado por Vec, entre otros tipos.
  • [1:21:21] collect funciona porque Vec implementa fromIterator.
  • [1:21:30] Llamar a collect en un iterador requiere que el tipo objetivo implemente fromIterator.

Mecánica de los traits FromIterator y Extend de Rust

parámetros de tipo del trait FromIterator

  • [1:21:38] Recolectar un iterador en un Vec funciona porque Vec implementa FromIterator.
  • [1:21:49] El tipo asociado A de FromIterator es el tipo de los elementos del iterador, por lo que resulta un Vec de ese tipo de elemento.
  • [1:22:00] El parámetro genérico T del trait es el tipo del iterador mismo, como el tipo de iterador de un HashMap.
  • [1:22:10] Un Vec<T> puede construirse a partir de cualquier iterador cuyo elemento sea T, independientemente del tipo concreto del iterador.
  • [1:22:20] El ponente señala que el parámetro probablemente debería llamarse I de iter, pero lo considera poco importante.

Problema del objeto trait con FromIterator

  • [1:22:43] Usar FromIterator plantea un problema para un objeto trait.
  • [1:23:35] Una función que toma un FromIterator de bool y devuelve un Vec parece que debería estar bien.
  • [1:23:45] FromIterator es un mal ejemplo porque no toma self, así que requiere que self tenga tamaño de todos modos.

Extend como un mejor ejemplo

  • [1:23:53] El ponente cambia a Extend como un mejor ejemplo.
  • [1:24:04] Extend toma un self mutable, así que el código crea un Vec mutable con Vec::new.
  • [1:24:25] El Vec se extiende con un solo bool, true, mediante v.extend.
  • [1:24:39] La función acepta cualquier cosa que pueda extenderse con un iterador de bools.

Por qué Extend no es object safe

Método genérico Extend y monomorfización

  • [1:25:05] Extend es genérico sobre el tipo de elemento del iterador, y aunque toma self, el método también es genérico sobre el tipo de iterador.
  • [1:26:28] Debido a la monomorfización, el compilador no produce un único método extend sino múltiples copias, una por cada combinación de tipos de iterador y de elemento.
  • [1:27:27] No hay un único extend; hay uno para cada combinación de tipos de iterador y de elemento.

Entrada de vtable faltante para la implementación elegida

  • [1:27:42] El tipo de elemento T ya está fijado como bool, pero la vtable todavía necesita un puntero para extender el tipo de iterador específico sobre bool.
  • [1:28:05] Ese tipo de iterador no se expresa en el tipo de la función, y no hay forma de expresarlo tal como está escrito.
  • [1:28:42] Cuando el compilador intenta generar el código, no hay ningún puntero a la implementación de extensión adecuada, por lo que no se puede generar la vtable.

Vtable infinita y sin objeto trait

  • [1:28:52] Una vtable para dyn Extend necesitaría un número infinito de entradas, una por cada posible implementación de extend.
  • [1:29:04] Por lo tanto, dyn Extend no puede existir, y no se puede crear un objeto trait para Extend.

Por qué fallan las vtables monomorfizadas por llamada

  • [1:29:26] Añadir un extend monomorfizado para cada T a cada tipo implementador es tentador, pero no siempre es posible.
  • [1:29:43] Los crates que dependen de la biblioteca estándar pueden llamar a extend con más tipos, por lo que la vtable para dyn Extend diferiría entre la biblioteca estándar y los crates superiores.
  • [1:30:18] Esto causaría una explosión combinatoria de diferentes vtables para dyn Extend y evitaría pasar un dyn Extend desde la biblioteca estándar al código de un crate superior, porque sus tipos de vtable difieren.

Seguridad de objetos y el trait Clone

Requisitos para traits seguros para objetos

  • [1:31:01] Para que un trait sea seguro para objetos, no debe tener métodos genéricos.
  • [1:31:10] Todos sus métodos deben tener un receptor que incluya self.
  • [1:31:17] El trait tampoco puede tener un tipo que devuelva self.

Por qué Clone no puede convertirse en un objeto trait

  • [1:31:38] Con un dyn Clone, solo se puede hacer lo que el trait permite, y Clone solo permite clonar.
  • [1:31:47] El compilador informa que el trait Clone no se puede convertir en un objeto.
  • [1:31:58] Clone tiene un fn clone que toma self y devuelve self.

Problema del tipo de retorno sin tamaño

  • [1:32:03] Para let x = v.clone(), el tamaño de x no está claro porque dyn Clone es simplemente cualquier tipo clonable.
  • [1:32:19] Se supone que Clone devuelve self, no una referencia a dyn Clone.
  • [1:32:26] Como el tipo concreto se borra, self sería dyn Clone, que no tiene tamaño.
  • [1:32:46] El tipo de retorno de una función debe tener tamaño para generar código, así que esto no puede funcionar.
  • [1:32:51] Por lo tanto, un trait no puede tener métodos que devuelvan self si va a ser seguro para objetos, y por eso no se puede usar Clone.

Mezclar métodos seguros para objetos y no seguros para objetos

  • [1:33:05] Algunos métodos de un trait pueden ser seguros para objetos y seguir siendo útiles por sí solos.
  • [1:33:12] Otros métodos pueden hacer que el rasgo no sea seguro para objetos, pero se desean para tipos que no pasan por un objeto de rasgo.

Seguridad para objetos del rasgo Iterator mediante where Self: Sized

Métodos genéricos de Iterator y seguridad para objetos

  • [1:33:23] El rasgo Iterator tiene el tipo asociado Item y el método seguro para objetos next, pero también métodos genéricos como chain, enumerate, by_ref y collect, que depende de FromIterator y no es seguro para objetos.
  • [1:34:01] Iterator es no obstante seguro para objetos: en un dyn Iterator<Item = bool>, collect no se puede invocar sobre el objeto de rasgo, pero next sí se puede llamar con un receptor mutable.

where Self: Sized excluye métodos de la vtable

  • [1:35:03] Métodos como count y last, que consumen self, llevan la restricción where Self: Sized, al igual que el método genérico chain.
  • [1:35:27] La restricción where Self: Sized indica al compilador que ignore esa función cuando se usa el rasgo como objeto de rasgo, por lo que no se coloca en la vtable.
  • [1:35:44] Por tanto, un objeto de rasgo no puede llamar a tal método, pero un tipo concreto como un iterador Vec sí puede, lo que permite que un rasgo conserve métodos deseables sin hacer que todo el rasgo deje de ser seguro para objetos.

Pregunta sobre los tipos de receptor permitidos

  • [1:36:13] El ponente pregunta si el receptor puede ser cualquier cosa que incluya self o debe ser &self o &mut self.

Reglas de seguridad para objetos de Rust y objetos de rasgo

Supertraits y constantes asociadas

  • [1:36:37] Todos los supertraits también deben ser seguros para objetos, porque la vtable se construye a partir de la unión de todos los supertraits.
  • [1:36:45] Exigir self: Sized hace que un rasgo no sea seguro para objetos, ya que Sized no sería un supertrait.
  • [1:36:52] Un rasgo seguro para objetos no debe tener constantes asociadas, porque no hay dónde colocarlas; ponerlas en la vtable la haría muy grande y sus valores ya no serían todos punteros a función.

Funciones despachables y no despachables

  • [1:37:12] Todas las funciones asociadas deben ser despachables desde un objeto trait o ser explícitamente no despachables.
  • [1:37:19] Las funciones despachables no deben tener parámetros de tipo (sin genéricos) y no deben usar el tipo concreto self excepto en el tipo del receptor, por lo que una función no puede devolver self.
  • [1:37:32] El receptor solo puede ser una referencia a self, una referencia mutable a self, Box<Self>, Rc<Self>, Arc<Self> o Pin<&Self>—cualquier cosa detrás de un puntero que pueda convertir un valor no dimensionado en uno dimensionado.
  • [1:37:55] Esto excluye explícitamente las restricciones where Self: Sized, lo que permite que un trait sea object safe incluso cuando algunos de sus métodos no lo son.

Consejo sobre añadir where Self: Sized

  • [1:38:14] Los autores de bibliotecas generalmente deberían considerar añadir where Self: Sized a los métodos no object-safe en caso de que los usuarios posteriores quieran un objeto trait.
  • [1:38:23] Depende de si el trait es utilizable como objeto trait en absoluto; para algo como Clone, añadir la restricción permitiría crear un objeto trait pero no llamar a su función principal, así que probablemente no vale la pena.
  • [1:38:48] Si un trait es útil incluso cuando solo se pueden llamar sus métodos object-safe, puede tener sentido excluir los otros métodos para que el trait en general sea object safe.

Iterator::last y la restricción Sized

  • [1:39:14] Iterator::last sí tiene la restricción Sized, oculta por rustdoc.
  • [1:39:25] last tiene where Self: Sized porque consume self en lugar de tomarlo detrás de una referencia; Self es un iterador que no es Sized, y los argumentos de función deben ser Sized, por lo que last no puede llamarse a través de un objeto trait.

Un secreto sobre los objetos de rasgo

  • [1:39:55] El ponente señala que hay al menos una cosa más que aún no se ha cubierto sobre los objetos trait: un pequeño secreto con los objetos trait.

Drop y las vtables de objetos trait

Drop como trait object-safe

  • [1:40:16] Drop es en realidad object safe, aunque un objeto que solo puede ser dropeado pueda parecer poco interesante.
  • [1:40:26] Esto es útil en situaciones como la recolección de basura, donde los objetos no se dropean inmediatamente sino que se almacenan en una lista enlazada y se recogen periódicamente.
  • [1:40:43] Almacenar muchas cosas potencialmente diferentes en un solo tipo requiere TraitObjects, por lo que Crossbeam las almacena en drops, técnicamente boxeadas en drops, con el mismo efecto.

Drop a través de la vtable

  • [1:40:59] Cuando v sale de ámbito, se llama a dropDrop a través de la vtable.
  • [1:41:34] Cuando un s boxeado sale de ámbito, existe una asignación en el heap que puede usarse mediante s.asref antes de que s sea dropeado al retorno de la función.
  • [1:41:56] Dropear una caja requiere liberar la memoria, pero un objeto trait cuyo único método es asref aún necesita una forma de hacerlo.
  • [1:42:06] Cada vtable incluye drop, por lo que la vtable de cualquier TraitObject incluye un puntero a la función drop para el tipo concreto, lo cual es necesario.

Tamaño y alineación en la vtable

  • [1:42:27] La vtable también incluye técnicamente el tamaño y la alineación del tipo concreto.
  • [1:42:34] Esa información se necesita para algo como una caja, donde debe pasarse al asignador para desasignar la memoria.
  • [1:42:44] La vtable de cada objeto trait incluye los métodos del trait más drop más tamaño más alineación.

Tipos no dimensionados y punteros anchos en Rust

Tipos sin tamaño más allá de los objetos trait

  • [1:43:04] Además de los objetos trait, otros tipos tampoco tienen tamaño, como [u8] y str.
  • [1:43:20] Cuando se coloca detrás de una referencia o puntero, un objeto trait se convierte en una tupla de un puntero a datos y un puntero a vtable.
  • [1:43:34] Un slice detrás de un puntero se convierte en un puntero ancho con un puntero a datos y un usize que contiene la longitud del slice.
  • [1:43:50] De forma similar, str detrás de un puntero se representa como un puntero a datos más una longitud usize.

Errores del compilador para argumentos y valores de retorno sin tamaño

  • [1:43:57] Una función que recibe [u8] por valor se rechaza porque el tamaño del valor de tipo [u8] no se conoce, ya que [u8] es una lista de u8 de longitud arbitraria.
  • [1:44:21] Devolver un [u8] desnudo también falla porque el tipo de retorno de una función debe tener un tamaño conocido estáticamente.

Enmascarar la falta de tamaño con referencias y Box

  • [1:44:59] Pasar de sin tamaño a con tamaño se logra colocando el valor detrás de un tipo que enmascara la falta de tamaño, como una referencia o Box.
  • [1:45:33] Boxear el slice está bien porque ahora tiene tamaño: un puntero ancho cuyas partes son los datos y la longitud.
  • [1:45:43] El compilador sabe deconstruir el puntero para obtener la longitud cuando se accede al tipo, y lo mismo se aplica a Box, los punteros crudos y String.

Tipos sin tamaño y metadatos de punteros gordos en Rust

Desafíos del compilador con tipos de tamaño dinámico

  • [1:46:04] Los tipos de tamaño dinámico son algo especiales en el compilador porque este debe saber si un puntero es ancho.
  • [1:46:14] Tratar con tipos sin tamaño uno mismo es bastante difícil, aunque implementar algo como box para un tipo sin tamaño es posible.
  • [1:46:27] Se vuelve molesto una vez que intervienen los casts y se permiten objetos trait.

RFC 2580 y el trait Pointy

  • [1:46:33] Un RFC recientemente publicado, el número 2580, añade una API genérica para manipular los metadatos de punteros gruesos.
  • [1:46:48] La API permite especificar el tipo de la segunda parte de un puntero grueso.
  • [1:46:58] Un trait DIN se convierte en un trait pointy cuyos metadatos son metadatos DIN, un puntero a una vtable que contiene el tamaño del tipo, la alineación, los punteros drop y place, y los punteros a métodos.
  • [1:47:28] El trait pointy podría implementarse de forma similar para un slice de U8 sin la referencia, con una longitud de tamaño U como metadatos.

Estado experimental y alias de trait Thin

  • [1:47:44] La característica aún es nueva y experimental, y el ponente recomienda leer el RFC.
  • [1:47:52] El RFC incluye un alias de trait thin para cualquier tipo que implemente pointy con metadatos vacíos, es decir, punteros thin en lugar de gruesos.

Introspección de metadatos y vtables en tiempo de ejecución

  • [1:48:08] El RFC proporciona métodos para introspectar los metadatos del puntero, como examinar la vtable.
  • [1:48:18] De manera crucial, permite construir vtables sobre la marcha que no se conocen en tiempo de compilación sino que se construyen en tiempo de ejecución.

Raw Waker como ejemplo de vtable manual

  • [1:48:32] La construcción de vtables en tiempo de ejecución ya existe en un lugar de la biblioteca estándar, para los wakers en async.
  • [1:49:14] El contexto te proporciona una estructura Waker con los métodos wake, wake by ref, willWake y fromRaw, y se puede soltar y clonar.
  • [1:49:29] Dentro de un Waker hay un RawWaker, que es un puntero a datos y un puntero a vtable, lo que proporciona despacho dinámico de forma oculta.
  • [1:49:54] Una vtable de RawWaker se construye proporcionando punteros a funciones para clone, wake, wake by ref y drop, efectivamente una vtable construida manualmente que proporciona despacho dinámico a través de un tipo en lugar de un trait.

DSTs de Rust, slices y Box vs Vec

Metadatos de slice y tipos personalizados de tamaño dinámico

  • [1:50:38] El ponente no está seguro de si una referencia a un slice de U8 almacena un puntero de inicio y fin o una longitud, y señala que ambos son básicamente equivalentes.
  • [1:51:01] El RFC referenciado depreca el objeto trait y los metadatos delgados de los elementos de partes crudas que existen en Nightly, porque es un reemplazo.
  • [1:51:29] El ponente esperaba que el RFC indicara el tipo de metadatos asociado para los slices, pero no lo ve, y cree que es simplemente la longitud.
  • [1:51:46] Se pueden crear tipos de tamaño dinámico propios: una estructura con un slice de u8 como último campo se vuelve de tamaño no fijo.
  • [1:52:14] Solo el último campo de una estructura puede tener un tipo de tamaño dinámico, porque el desplazamiento de un campo intermedio no podría calcularse si el tipo precedente tiene tamaño arbitrario.
  • [1:53:07] Si el campo de tamaño no fijo es el último, los desplazamientos de los campos anteriores se conocen estáticamente y solo se necesita la longitud del último campo para que el tipo tenga tamaño fijo.
  • [1:53:18] Una referencia a dicha estructura tiene tamaño fijo almacenando el puntero junto con la longitud del último campo.

Box<[u8]> frente a Vec<u8>

  • [1:53:42] Un slice de u8 boxeado que no está detrás de una referencia no es lo mismo que un Vec<u8>, aunque se sientan igual.
  • [1:54:11] Un Vec son tres palabras: un puntero al vector en el heap, su longitud y su capacidad, por lo que hacer push dentro de la capacidad solo incrementa la longitud.
  • [1:54:32] Hacer push más allá de la capacidad de un Vec reasigna el vector completo, lo copia y luego lo modifica.
  • [1:54:39] Un slice u8 boxeado nunca puede crecer ni encogerse y no se le puede hacer push; en realidad es solo un slice.
  • [1:54:49] Un Vec<u8> se puede convertir en un Box<[u8]> y viceversa, pero no son el mismo tipo.

dyn fn vs fn vs impl fn en Rust

fn como un puntero a función simple

  • [1:55:53] Un parámetro fn debe ser una función y no puede ser un closure, porque fn en realidad es solo un único puntero a función que contiene una dirección.
  • [1:57:35] bar requiere un puntero a función real, por lo que no se puede pasar un closure porque no habría dónde almacenar los datos capturados.

dyn fn como un objeto trait de puntero ancho

  • [1:56:02] Un dinfn es un objeto trait cuya vtable contiene un puntero para llamar a la función, y es un puntero ancho que también incluye un puntero a datos.
  • [1:57:10] foo se puede llamar con un closure que captura x porque el closure necesita la dirección de x proporcionada a través de la parte de datos del puntero ancho cuando se llama.

impl fn como monomorfización genérica

  • [1:58:24] baz se puede llamar con un closure porque implfn es azúcar para una función genérica sobre cualquier cosa que sea fn, produciendo una copia concreta de baz para cada tipo de closure pasado.
  • [1:58:40] Como baz se monomorfiza para cada closure individual, los datos capturados se pueden pasar de forma trivial.

Elegir entre impl fn y dyn fn

  • [1:58:53] implfn es más generalmente usable y evita la indirección tras un puntero, pero genera una copia de baz para cada tipo de closure pasado, lo que podría llegar a ser bastante.
  • [1:59:12] A veces se prefiere un objeto trait sobre los genéricos porque, de lo contrario, el tipo genérico tiene que propagarse hasta los llamadores.
  • [1:59:51] Si una struct envoltorio almacena un box din fn en lugar de ser genérica sobre f, el envoltorio deja de ser genérico, por lo que los llamadores no tienen que nombrar ni propagar el parámetro genérico, lo que puede limpiar la interfaz.

Object safety de traits con parámetros fn

  • [2:00:19] Un trait x cuyo foo toma un impl fn no es object safe, porque implfn es equivalente a un f genérico que es fn y esto no se puede hacer object safe.
  • [2:01:07] Si foo en cambio toma un dinfn, el trait puede ser object safe porque solo hay un foo, evitando la necesidad de un número infinito de entradas de vtable, y foo mismo toma un puntero ancho que funciona para cualquier tipo object safe.

Coherencia diferida; preguntas y respuestas sobre despacho, vtables y detección de traits

Diferir la coherencia a un stream separado

  • [2:02:00] La coherencia no se cubrió y es lo suficientemente diferente como para que el ponente pueda hacer un stream separado sobre ella.
  • [2:02:15] Como el stream está alrededor de la marca de las dos horas, el ponente cree que es un buen momento para detenerse y tratar la coherencia por separado.

Resumen de los conceptos de despacho y objeto de rasgo

  • [2:02:29] El ponente pregunta si la diferencia general entre despacho estático y despacho dinámico, el rasgo size, las vtables, la seguridad de objetos y los punteros anchos y gruesos se entiende aproximadamente.
  • [2:02:45] El ponente se ofrece a repasar más material para aclarar por qué existen estos conceptos, para qué sirven y cuáles son sus limitaciones.

Por qué la detección de rasgos en tiempo de ejecución mediante vtables no es posible

  • [2:03:00] A la pregunta de si la detección de rasgos en tiempo de ejecución podría implementarse en el futuro usando vtables, el ponente dice que no cree que sea posible.
  • [2:03:30] Se genera una vtable diferente para cada objeto de rasgo, así que no hay una sola vtable para str o string sino muchas vtables para string, una por cada dyn trait.
  • [2:04:02] Para una función que toma un S que es un dyn trait, la vtable contendría solo los métodos del rasgo nombrado, no todos los métodos posibles del tipo proporcionado.
  • [2:04:30] Por lo tanto, el ponente no cree que la detección dinámica de qué rasgos implementa algo pueda hacerse de esta manera.

Doble desreferencia en llamadas a dyn Fn

Diseño del puntero ancho para dyn Fn

  • [2:05:23] La llamada no es exactamente una doble desreferencia porque el argumento es un puntero ancho, no un puntero a una tupla de un puntero y una vtable.
  • [2:05:33] Lo que se pasa es un puntero a algún T cuyo tipo es desconocido, más un puntero a la vtable Fn de T.

Desreferencia de la vtable para llegar a la llamada

  • [2:05:56] La llamada se convierte efectivamente en Vtable.call de t, así que el puntero a la vtable debe desreferenciarse para llegar a la llamada.
  • [2:06:28] Se desreferencia la vtable para encontrar la dirección de la llamada que luego se invoca, así que termina siendo dos desreferencias.
  • [2:06:35] Aun así, no es exactamente persecución de punteros.

Despacho dinámico, trucos con vtables y optimización genérica

Comparación de vtables para downcasting

  • [2:07:02] Para un tipo X que implementa AsRef<str>, el nuevo RFC de metadatos dinámicos de vtable de puntero podría permitir comparar s.vtable con la vtable de una implementación de string AsRef<str>.
  • [2:07:41] Si las vtables coinciden, se podría convertir la referencia de datos en una referencia a string y, para una referencia mutable, llamar a push, aunque el ponente recomienda no hacerlo.
  • [2:08:07] El ponente no está seguro de si el compilador garantiza que un tipo siempre tenga exactamente una vtable.

Genéricos frente a optimización de despacho dinámico

  • [2:08:18] El compilador realiza una cantidad decente de optimización, y un boxed dyn fn puede no siempre asignar en el heap debido al análisis de escape y técnicas similares.
  • [2:08:31] Usar un parámetro de tipo genérico o impl trait generalmente produce una mejor optimización porque el compilador tiene plena visibilidad en tiempo de compilación de los tipos relevantes y puede cooptimizar basándose en implementaciones concretas.
  • [2:08:52] Con la indirección mediante despacho dinámico, el compilador pierde parte de la información que de otro modo usaría para la optimización.

Ejemplo de slice solicitado

  • [2:09:07] Un oyente pide un ejemplo rápido de un slice Vec de dyns.

Objetos trait de Rust, vtables y el trait Any

Hacer que los arrays dyn AsRef funcionen con elementos de tamaño definido

  • [2:09:15] Para usar algo como dyn AsRef<str> para H y S, debes hacer que los elementos del array tengan el mismo tamaño, porque el array lo requiere para que se pueda encontrar un índice dado.
  • [2:09:56] Una vez que los elementos tienen el mismo tamaño, el enfoque simplemente funciona, y también puedes poner un Box o Arc o similar para el tipo interno.

Por qué las vtables pueden diferir entre unidades de compilación

  • [2:10:08] Distintas unidades de compilación pueden dar lugar a distintas vtables.
  • [2:10:12] Anecdóticamente, Rust puede compilar un crate usando múltiples hilos independientes para compilar distintos subconjuntos y acelerar la compilación.
  • [2:10:25] Como esas unidades separadas trabajan de forma concurrente sin mucha sincronización, ambas podrían encontrar un string usado como dyn AsRef y cada una generar sus propias vtables en lugar de coordinarse.
  • [2:10:40] Esto puede producir múltiples vtables incluso para el mismo tipo y el mismo trait, lo cual es un ejemplo de por qué el invariante podría no cumplirse.

Cómo el trait Any permite el downcasting

  • [2:10:57] El trait Any se describe como súper mágico, pero es solo un trait con una función que devuelve un identificador de tipo garantizado único por el compilador.
  • [2:11:19] Con un objeto trait sobre Any, puedes usar el ID de tipo en él porque se añade a la vtable, obteniendo un identificador de tipo único para ese valor.
  • [2:11:28] Ese identificador te permite hacer downcast de un dyn Any al tipo concreto porque sabes cuál es el identificador de tipo.
  • [2:11:46] Any usa gran parte de la maquinaria discutida anteriormente para pasar de un dyn trait, siempre que ese trait incluya Any, a una referencia al tipo subyacente real.

Lectura recomendada sobre la seguridad de Any

  • [2:12:02] El ponente dice que Any es sorprendentemente simple una vez que conoces los conceptos subyacentes y recomienda leer la documentación estándar de AnyModule.
  • [2:12:12] Esa documentación explica por qué esto es seguro.

Resumen de la transmisión y planes futuros de programación

Conclusión y duración de la sesión

  • [2:12:17] El ponente termina la sesión a las aproximadamente 2 horas y 15 minutos y dice que está bastante satisfecho con ella.
  • [2:12:22] Señala que se cubrió mucho y espera que haya sido útil y que parte de ello pueda perdurar.

Transmisión en vivo de programación planificada

  • [2:12:30] Dice que ha avanzado un poco en la transmisión en vivo de programación que realmente quiere que se realice y espera que ocurra cuanto antes.
  • [2:12:39] Dice que no ha olvidado el plan y que sigue ocupándose de ello.

Agradecimiento final

  • [2:12:44] Agradece a todos por haber venido y dice que los verá la próxima vez.

Lee los subtítulos disponibles con marcas de tiempo o transcribe podcasts, clases y audio o vídeo local. Extractor gratuito de subtítulos de YouTube.

[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!

Abrir en el lector de Vidleaf

Busca citas exactas entre comillas, compara subtítulos bilingües y exporta TXT, SRT o Markdown con marcas de tiempo.

Atribución y licencia

«Crust of Rust: Dispatch and Fat Pointers» por Jon Gjengset (https://www.youtube.com/@jonhoo), con licencia CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Vídeo original: https://www.youtube.com/watch?v=xcygqF5LVmM. Esta página presenta una transcripción con marcas de tiempo; la persona o entidad creadora no está afiliada a Vidleaf ni lo avala.

¿Eres el autor o titular de derechos? Solicita correcciones o retirada en copyright@vidleaf.app.

Última actualización