Convert Vec<[u32; 2] to bytes|String|&str?


#1

How so I convert a Vec<[u32; 2] into bytes|String|&str ?
I’ve tried so many options for this and not getting anyway.

For example a vec = [[283, 16], [23, 626]]; should become a string “[[283, 16], [23, 626]”.

I don’t understand entirely why to_string() and other simple functions, cannot accept anything that can already be output to print! as string, with debug or default print!(). Obviously, going the other way should not be easy but I wonder that something becoming a string shouldn’t require fragmenting or whatever extra step is here.


#2

I’m assuming you are asking why print!("{:?}", vec![[283, 16], [23, 626]]) works, but vec![[283, 16], [23, 626]].to_string() doesn’t.

The answer is quite simple: during printing you chose {:?} instead of {}. The questionmark denotes that you wish to use Debug::fmt instead of Display::fmt. The to_string() method is only implemented for types that implement Display as you can see in the docs: https://doc.rust-lang.org/nightly/std/string/trait.ToString.html#tymethod.to_string

If you want to write to a string the same way you print, you need to use the write! macro:

use std::fmt::Write;

fn main() {
    let v = vec![[5, 3], [42, 99]];
    
    println!("{:?}", v);
    
    let mut s = String::new();
    write!(&mut s, "{:?}", v).unwrap();
    println!("{}", s);
}

#3
let s = format!("{:?}", v);

… seems to work too. Is there a benefit in using the longer write!() version?


#4

not for strings, but for general writing to buffers implementing the fmt::Write trait


#5

If you can predict the size of the output you can allocate once (String::with_capacity), while format! will likely have to reallocate several times as the string grows.


I32 to vector of i32