Write a generic function that joins items of any printable type into a string
Write describe_all, which takes a slice of items of any one type and returns their text separated by , — for example 1, 2, 3 for &[1, 2, 3].
Constraints:
- The signature has no trait bound yet: add to
Texactly the bound the body needs, and nothing more. - It works for
i32,&strand any other type that prints with{}; an empty slice gives an empty string, and there is no trailing separator. - Do not clone the items or take ownership of the slice.
fn describe_all<T>(items: &[T]) -> String {
// your code here: the bound on T and the body
}
fn main() {
println!("[{}]", describe_all(&[1, 2, 3])); // [1, 2, 3]
println!("[{}]", describe_all(&["a", "b"])); // [a, b]
println!("[{}]", describe_all::<i32>(&[])); // []
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Declare fn describe_all<T: Display>(items: &[T]) -> String: the Display bound is what lets the body call to_string() or use {} on an item. Push each item's text into a String with , between items; with no bound, to_string() is E0599.
- Leaving
Tunbounded and expecting the call site to supplyDisplay, as C++ templates do - Bounding
TbyDebug, which prints&stritems in quotes - Writing
&[dyn Display], a slice of unsized values that cannot exist
- Where does
to_string()come from when the bound only asks forDisplay? - How would you write the same body as one iterator chain instead of a loop?
The compiler checks the body of a generic function once, against its bounds, not for every substituted type. Without a bound T could be anything, and the call item.to_string() gives error E0599: the method exists only for types with Display. So the bound T: Display is exactly what the body needs and nothing more: the function needs neither Clone nor Debug.
use std::fmt::Display;
fn describe_all<T: Display>(items: &[T]) -> String {
let mut out = String::new();
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
out.push_str(&item.to_string());
}
out
}
fn main() {
println!("[{}]", describe_all(&[1, 2, 3])); // [1, 2, 3]
println!("[{}]", describe_all(&["a", "b"])); // [a, b]
println!("[{}]", describe_all::<i32>(&[])); // []
}to_string() comes from the blanket implementation impl<T: Display + ?Sized> ToString for T: every type with Display gets it for free. The separator goes before every item except the first, so there is none at the end, and an empty slice gives an empty string. The items are only read through &[T], so the function clones and takes nothing. With T: Debug instead of Display, strings would print in quotes: "a", "b". The chain items.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ") gives the same result, but it builds an intermediate vector.