Using Trait Objects That Allow for Values of Different Types - The Rust Programming Language
In Chapter 8, we mentioned that one limitation of vectors is that they can store elements of only one type. We created a workaround in Listing 8-9 where we defined a SpreadsheetCell enum that had variants to hold integers, floats, and text. This meant we could store different types of data in each cell and still have a vector that represented a row of cells. This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled. However, sometimes we want our library user to be able to extend the set of types that are valid in a particular situation. To show how we might achieve this, we’ll create an example graphical user interface (GUI) tool that iterates through a list of items, calling a draw method on each one to draw it to the screen—a common technique for GUI tools. We’ll create a library crate called gui that contains the structure of a GUI library. This crate might include some types for people to use, such as Button or
Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help In Chapter 8, we mentioned that one limitation of vectors is that they can store elements of only one type. We created a workaround in Listing 8-9 where we defined a SpreadsheetCell enum that had variants to hold integers, floats, and text. This meant we could store different types of data in each cell and still have a vector that represented a row of cells. This is a perfectly good solution when our interchangeable items are a fixed set…
related reading
- Defining Shared Behavior with Traits - The Rust Programming Languagedoc.rust-lang.org
- Storing Lists of Values with Vectors - The Rust Programming Languagedoc.rust-lang.org
- A half-hour to learn Rustfasterthanli.me
- Generic Types, Traits, and Lifetimes - The Rust Programming Languagedoc.rust-lang.org
- Idea Listjzhao.xyz
- Generic Data Types - The Rust Programming Languagedoc.rust-lang.org
- Defining an Enum - The Rust Programming Languagedoc.rust-lang.org
- Variance - Rust Compiler Development Guiderustc-dev-guide.rust-lang.org
- Reading 12: Defining ADTs with Interfaces, Generics, Enums, and Functionsweb.mit.edu
- Using Structs to Structure Related Datadoc.rust-lang.org
- Rust Language Cheat Sheetcheats.rs
- The Better Alternative to Lifetime GATs - Sabrina Jewsonsabrinajewson.org