liveBook · Manning

To_string method

As explained in Refactoring to Rust

The Rust to_string() method converts a value implementing ToString into an owned String.

The Rust to_string() method converts a string literal or other suitable value into an owned String. This is useful when data must be stored in a struct or passed to code that takes ownership. section 2.4.1 section 2.1

The conversion allocates a heap buffer and copies the source data, so repeated calls in a tight loop can hurt performance. The visible method call makes those allocations easier to find and limit. section 2.4.1

Creating owned struct data

A struct with a String field can convert its literal during initialization: let art1 = Artwork { name: "La Trahison des images".to_string() };. The resulting value owns its name and can be passed to a function taking Artwork. section 2.1

Converting for a String parameter

A function that accepts String can receive a literal after conversion: print_admiration("Artwork".to_string());. When a function only reads the value, accepting &str avoids requiring this allocation. section 2.4.1

How Refactoring to Rust covers it

How deep it goes
Explains allocation, copying, ownership, and the String-versus-&str choice, but stops short of implementing ToString directly.
Examples
Demonstrates artwork structs, function arguments, string literals, and conversions between String and &str.
What it assumes
Assumes basic Rust variables and structs while introducing the distinction between string literals, String, and &str.
What you can do after
Apply it to convert literals into owned String values and recognize allocation costs at conversion points.
How it connects
Connects to String, &str, ownership, borrowing, heap allocation, and performance.

Related concepts

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