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.

1 answer

  • answered 2022-01-13 05:54 Abdul Niyas P M

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum