Rust: trying to implement a trait on types that can contain implementing this trait

I’m trying to understand Rust traits and an exercise I had in mind was to implement a serializer.
The idea would be the following: it outputs things in the form <type=TYPE,value=VALUE> where TYPE and VALUE are placeholders for types and values.

The serializer would support a string type string and also an array type array. The array can contain any valid type, include the array type, in other words it can be nested.

These would be valid outputs:

  • for the string hello world: <type=string,value=hello world>,
  • for the array containing foo and bar: <type=array,value=[<type=string,value=foo>,<type=string,value=bar>]>,
  • for the array containing the array containing foo and then bar (in JSON it would be [["foo"], "bar"]) : <type=array,value=[<type=array,value=[<type=string,value=foo>]>,<type=string,value=bar>]>,
  • etc.

My idea was to provide a single function serialize that would take:

  1. something we can write into (for example a std::io::Write),
  2. a value implementing a Serializable trait.

When called, serialize would apply the Serializable implementation of the provided type:

pub mod serializer {
    pub fn serialize<W: std::io::Write, V: Serializable>(
        writer: &mut W,
        value: V,
    ) -> std::io::Result<()> {
        value.serialize(writer)
    }

    pub trait Serializable {
        fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>;
    }
}

Now, to support the string type, we can implement Serializable for &str:

pub mod serializer {
    pub fn serialize<W: std::io::Write, V: Serializable>(
        writer: &mut W,
        value: V,
    ) -> std::io::Result<()> {
        value.serialize(writer)
    }

    pub trait Serializable {
        fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>;
    }

    impl Serializable for &str {
        fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
            write!(writer, "<type=string,value={}>", self)
        }
    }

    #[cfg(test)]
    mod test {
        use super::serialize;

        #[test]
        fn test_serialize_str() {
            let mut buffer = Vec::new();
            serialize(&mut buffer, "hello world").unwrap();
            assert_eq!(
                String::from_utf8(buffer).unwrap(),
                "<type=string,value=hello world>"
            );
        }
    }
}

To implement the array serialization, I started by implementing Serializable for the Vec. However this approach works only when all values of the Vec are of the same type.

...
    impl<T: Serializable + Clone> Serializable for Vec<T> {
        fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
            write!(writer, "<type=array,value=[")?;
            let mut sep = "";
            for v in self {
                write!(writer, "{}", sep)?;
                serialize(writer, v.clone())?;
                sep = ","
            }
            write!(writer, "]>")
        }
    }
...
        #[test]
        fn test_serialize_vec_of_str() {
            let mut buffer = Vec::new();
            serialize(&mut buffer, vec!["hello", "world"]).unwrap();
            assert_eq!(
                String::from_utf8(buffer).unwrap(),
                "<type=array,value=[<type=string,value=hello world>,<type=string,value=hello world>]>"
            );
        }

To support arrays of any other type, I naively tempted to implement Serializable for Vec<Box<dyn Serializable>>. I understand Vec<Box<dyn Serializable>> as a Vec of anything that implements the Serializable trait.

    impl Serializable for Vec<Box<dyn Serializable>> {
        fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
            write!(writer, "<type=array,value=[")?;
            ...
            write!(writer, "]>")
        }
    }

However rust does not compile it, and yields the following errors.
What prevents Serializable to be implemented for Vec<Box<dyn Serializable>>?
The compiler then suggests to use an enum and dispatch according to it but I’m not sure to understand how it would help, is it linked or a different issue?

Thanks!

   Compiling playground v0.0.1 (/playground)
error[E0038]: the trait `Serializable` cannot be made into an object
  --> src/lib.rs:19:27
   |
19 |     impl Serializable for Vec<Box<dyn Serializable>> {
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^ `Serializable` cannot be made into an object
   |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> src/lib.rs:10:12
   |
9  |     pub trait Serializable {
   |               ------------ this trait cannot be made into an object...
10 |         fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>;
   |            ^^^^^^^^^ ...because method `serialize` has generic type parameters
   = help: consider moving `serialize` to another trait
   = help: the following types implement the trait, consider defining an enum where each variant holds one of these types, implementing `Serializable` for this new enum and using it instead:
             &str
             std::vec::Vec<std::boxed::Box<(dyn serializer::Serializable + 'static)>>
   = note: `Serializable` can be implemented in other crates; if you want to support your users passing their own types here, you can't refer to a specific type

error[E0038]: the trait `Serializable` cannot be made into an object
  --> src/lib.rs:20:42
   |
20 |         fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
   |                                          ^^^^ `Serializable` cannot be made into an object
   |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> src/lib.rs:10:12
   |
9  |     pub trait Serializable {
   |               ------------ this trait cannot be made into an object...
10 |         fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>;
   |            ^^^^^^^^^ ...because method `serialize` has generic type parameters
   = help: consider moving `serialize` to another trait
   = help: the following types implement the trait, consider defining an enum where each variant holds one of these types, implementing `Serializable` for this new enum and using it instead:
             &str
             std::vec::Vec<std::boxed::Box<(dyn serializer::Serializable + 'static)>>
   = note: `Serializable` can be implemented in other crates; if you want to support your users passing their own types here, you can't refer to a specific type

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật