1

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.

  • 5
    I believe the problem you're seeing comes from the "{:?}" in your println macro. The :? tells printlin to fall back to using the Debug trait to print the variable instead of the Display trait. The Debug trait for char is adding the backslashes. The best way to solve this really depends on what you are doing. Unfortunately you cannot implement Display on char yourself (as you cannot implement foreign traits on a foreign type), so if you really need to implement Display you'll need to wrap char in a tuple struct. – DeanBDean Jan 13 '22 at 05:47
  • 1
    Using the display trait works perfectly. I was actually printing a string built using a char vec and string implements the display trait. Was using the debug trait a lot so I guess it was just a muscle memory thing using it instead of the default display trait. Thanks! – Miguel Pinheiro Jan 13 '22 at 06:23

1 Answers1

4

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

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46