How do I create a heterogeneous collection of objects?

Trait objects The most extensible way to implement a heterogeneous collection (in this case a vector) of objects is exactly what you have: Vec<Box<dyn ThingTrait + ‘static>> Although there are times where you might want a lifetime that’s not ‘static, so you’d need something like: Vec<Box<dyn ThingTrait + ‘a>> You could also have a collection … Read more

What is the difference between iter and into_iter?

TL;DR: The iterator returned by into_iter may yield any of T, &T or &mut T, depending on the context. The iterator returned by iter will yield &T, by convention. The iterator returned by iter_mut will yield &mut T, by convention. The first question is: “What is into_iter?” into_iter comes from the IntoIterator trait: pub trait … Read more

Return local String as a slice (&str)

No, you cannot do it. There are at least two explanations why it is so. First, remember that references are borrowed, i.e. they point to some data but do not own it, it is owned by someone else. In this particular case the string, a slice to which you want to return, is owned by … Read more

How do I create a global, mutable singleton?

Non-answer answer Avoid global state in general. Instead, construct the object somewhere early (perhaps in main), then pass mutable references to that object into the places that need it. This will usually make your code easier to reason about and doesn’t require as much bending over backwards. Look hard at yourself in the mirror before … Read more

Traits and Rust

That block defines a new trait called Foo, which then allows you to use the trait in various places such as the impl block you have posted. The : Bar part says that any type that implements Foo must also implement the Bar trait.