Why doesn't Vec implement the Display trait?

前端 未结 1 1749
执笔经年
执笔经年 2020-12-12 00:55

Learning the language it\'s been surprising to me I cannot print an instance of Vec:

fn main() {
    let v1 = vec![1, 2, 3];
    println!(\"{}\"         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 01:00

    First, you can't implement a foreign trait for a foreign type, that's what the question and answer the link to which ker has provided are about.

    In principle, nothing prevents implementing Display for Vec in a module where either of them is defined (most likely in collections::vec). However, this is intentionally not done. As is explained in this and this RFCs, the Display trait is intended to produce strings which should be displayed to the user. However, there is no natural way to produce such a string from a vector. Do you want comma-separated items or tab-separated ones? Should they be wrapped in brackets or curly braces or nothing? Maybe you want to print each element on its separate line? There is no one single way.

    The simplest way to work around this would be to use a newtype wrapper. For example:

    use std::fmt;
    
    struct SliceDisplay<'a, T: 'a>(&'a [T]);
    
    impl<'a, T: fmt::Display + 'a> fmt::Display for SliceDisplay<'a, T> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut first = true;
            for item in self.0 {
                if !first {
                    write!(f, ", {}", item)?;
                } else {
                    write!(f, "{}", item)?;
                }
                first = false;
            }
            Ok(())
        }
    }
    
    fn main() {
        let items = vec![1, 2, 3, 4];
        println!("{}", SliceDisplay(&items));
    }
    

    0 讨论(0)
提交回复
热议问题