Miguel Pinheiro
Miguel Pinheiro

Reputation: 342

Vec<char> with escaped chars printing the \ in rust

I'm trying to get a Vec containing the symbols ' " and \.

Minimal reproducible example of whats wrong is

println!("{:?}", vec!['\'', '\"', '\\'])

or

let vector: Vec<char> = "\'\"\\".chars().collect();
println!("{:?}", vector)

That outputs

['\'', '"', '\\']

Here only the " case is printing correctly.

Desired output would be

[', ", \]

Am I doing something wrong? I'm using rustc 1.56.1.

Upvotes: 1

Views: 502

Answers (1)

user459872
user459872

Reputation: 24562

This is because you are using {:?}(Debug Trait) formatter which is mainly for debugging purposes. But unfortunately vector does not implement {}(Display Trait) which can be used to format text in a more elegant, user friendly fashion (like in your case). So if you try the following

println!("{}", vector)

Rust will complain with the following error.

`Vec<char>` doesn't implement `std::fmt::Display`

So one solution is to implement Display trait for the wrapper type.

use std::fmt;

struct MyVec(Vec<char>);

impl fmt::Display for MyVec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if &self.0.len() == &0usize {
            write!(f, "[]")?;
        } else {
            write!(f, "[")?;
            for (index, val) in self.0.iter().enumerate() {
                if index > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", &val)?;
            }
            write!(f, "]")?;
        }
        Ok(())
    }
}

fn main() {
    let vector: Vec<char> = "\'\"\\".chars().collect();
    let f = MyVec(vector);
    println!("{}", f);
}

This will print

[', ", \]

See also

Upvotes: 4

Related Questions