liveBook · Manning

Dynamically sized type

As explained in Learn Rust in a Month of Lunches

A dynamically sized type is a type whose size is not known at compile time and may vary between values.

A dynamically sized type has a size that can vary between values, so Rust cannot determine its exact size at compile time. A string slice, written str, is one example: different text values occupy different amounts of memory. section 2.2

Because Rust must know the size of local variables, you normally use &str instead of str. The reference has a known size and points to the text elsewhere. String is different: it is sized and can own variable-length text. section 2.2

Comparing text sizes

The text "자우림" and "Adrian Fahrenheit Țepeș" have different byte lengths. std::mem::size_of_val can measure each value, while size_of::<String>() reports String's fixed representation size. Attempting let my_name: str = "My name" produces an error; changing the type to &str supplies the needed reference.

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines dynamic sizing, measures concrete values, and follows an invalid str declaration through compiler feedback to a borrowing fix.
Examples
Uses multilingual names, an emoji, memory-size functions, and an invalid str variable corrected to &str.
What you can do after
Apply via Rust syntax by choosing &str for borrowed text, String for owned text, and size_of_val for value measurements.
How it connects
Connects dynamically sized types with string slices, references, ownership, UTF-8, stack storage, and compile-time sizing.

Also explained in

Compare how 2 books explain dynamically sized type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.