Emitting a Vec<&str> of random values


I have what I think is a fairly simple task: I want to emit a stream of random values from a server. I happen to be using ws-rs, so the data type in the response is a Vec<&str>.

I can arbitrarily choose how long the sequence is, say "200", and I use rng.gen_ascii_chars().take(200).collect() to create a collection of random characters.

  "/rng" => {
    const NUMNUM: usize = 200;
    let mut vec: Vec<&str> = Vec::with_capacity(NUMNUM);
    let mut rng = rand::XorShiftRng::new_unseeded();

    let chars = rng.gen_ascii_chars().take(NUMNUM).collect();
    // and then?

    self.inner = Box::new(Data {
      ws: out,
      data: vec

I am utterly stumped trying to transpose each entry from the random number generator's collection into an entry in the vector.

My assumption is to stringify each character and push it onto the vector. Unfortunately, lifetime of the stringified character is biting me whenever I then attempt to dereference each String and push it onto the Vec<&str>.

It's a shame that the scoping rules for lifetime don't cater for stream processing (e.g. a series of map(), filter(), etc functions) because that would be the "functional" approach.

Any tips / epiphanies appreciated.


Where does Data come from? I took a look at one of the examples for ws-rs and it seems the Data struct is user-implemented, so you would just change it to contain a Vec<String>, as the String is owned and heap-allocated and you can thus pass it on.

To collect your ASCII characters into a vector of Strings:

let chars = rng.gen_ascii_chars().take(10)
               .map(|w| format!("{}", w))

By the way, this generates random ASCII characters, not random numbers.

Thanks @jer! I'll take a look at how and where Data is declared and adjust accordingly. Your approach is certainly understandable. Very much appreciated.

(I've altered the question to reflect that the particular type of values needn't be numbers or characters in particular, I just thought it'd be simpler to use chars)

Yes, that works right up until Data is then handled by a ws::Handler which sends it back to the client. I'm working on that dealing with a String now. Cheers!