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

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.

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: ToString in std::string - Rust

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);
}
1 Like
let s = format!("{:?}", v);

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

2 Likes

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

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.

1 Like