Skip to content

← Collections, Text and First Iterators step 4 of 21

Easy Primitives

Joining owned strings

Take ownership of a Vec<String> and produce a single String with the words separated by one space.

pub fn solve(words: Vec<String>) -> String

["hello", "world"] becomes "hello world". An empty vector becomes "", and a single word becomes itself — no leading or trailing separator.

The point of this problem is not the algorithm. A C-brained first draft reaches for a for loop, a push_str, and an if to avoid the trailing space. That compiles, and clippy -D warnings will still reject it: the standard library already has exactly this operation, and a reviewer expects you to use it.

Two things worth noticing while you write it:

  • words is taken by value, so this function owns the vector. The caller gave it away. That is a deliberate choice for this exercise — think about whether a &[String] would have been a better signature, and what it would cost the caller either way.
  • The separator method is defined on slices, not on Vec — and a Vec derefs to a slice automatically. That coercion is doing quiet work here, and it is worth knowing it happened.

Remember the grade is compile + tests + clippy -D warnings.

Loading visualization…