Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print elements in a vector contiguously

I would like to know which is the most idiomatic Rust way to print the elements in a vector in a contigously manner. For example, in the following code:

fn main() {
    let vector = vec![0x54, 0xaf, 0x5c];
    println!("{:2x?}", vector);
}

I would like to print: 54af5c and not [54, af, 5c].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to do this in one line without multiple calls to the print! macro you could do it like so:

fn main() {
    let vector = vec![0x54, 0xaf, 0x5c];
    println!("{}", vector.iter().map(|n| format!("{:x}", n)).fold(String::new(), |acc, arg| acc + arg.as_str()));
}

Here is the Playground.

This also has the added benefit, that there can be differently formatted hexadecimal numbers in your vector and you can always format them as either LowerHex or UpperHex.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading