0

Is there a more elegant way of chunking an array and then joining it?

fn main() {
    let size = 4;
    let buffer = vec![0; size * size];

    let pbm = format!(
        "P4\n{} {}\n{}",
        size,
        size,
        buffer
            .chunks(size)
            .map(|chunk| chunk
                .into_iter()
                .map(|x| x.to_string())
                .collect::<Vec<String>>()
                .join(" "))
            .collect::<Vec<String>>()
            .join("\n")
    );

    println!("{:?}", pbm);
}

Why do I have to precise type to collect? Shouldn't it find it out by at what map returns?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Luke Skywalker
  • 1,464
  • 3
  • 17
  • 35
  • You can collect into any type that implements `FromIterator`. So not precising the type is ambiguous. – Denys Séguret Jul 16 '19 at 14:46
  • Relevant: https://stackoverflow.com/q/30972047/1233251 – E_net4 Jul 16 '19 at 14:52
  • Both times that you use `collect`, you then call `join()`. Rust doesn't know which implementation of `join` you mean until it knows the type returned by `collect`. – Peter Hall Jul 16 '19 at 14:52
  • 2
    Note that in the general case, if you want to display your matrix, you'd better define a struct implementing Display and wrapping your buffer rather than use intermediate strings. You can do the whole without any String. – Denys Séguret Jul 16 '19 at 14:55
  • Also relevant: [What's an idiomatic way to print an iterator separated by spaces in Rust?](https://stackoverflow.com/questions/36941851/whats-an-idiomatic-way-to-print-an-iterator-separated-by-spaces-in-rust) – trent Jul 16 '19 at 15:06
  • @DenysSéguret could you please create an answer and illustrate your proposal? – Luke Skywalker Jul 16 '19 at 15:19
  • @LukeSkywalker I can't as the question is closed – Denys Séguret Jul 16 '19 at 15:43
  • @LukeSkywalker Here's the kind of solution I had in mind: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=309ec420b04925f9f84bd03a9e25661f – Denys Séguret Jul 16 '19 at 15:46

0 Answers0