Unable to create a polymorphic type because the trait cannot be made into an object

前端 未结 2 1994
野性不改
野性不改 2020-12-11 16:10

I\'ve got this simplified Rust code:

use std::io::Result;

pub trait PacketBuffer {}

pub trait DnsRecordData {
    fn write(&self         


        
2条回答
  •  隐瞒了意图╮
    2020-12-11 16:45

    The intention is that DnsRecord should be able to hold any struct implementing the DnsRecordData trait

    That's not what the code says.

    Vec>
    

    This is a vector of the struct DnsRecord containing the trait DnsRecordData. If you want "any struct implementing the DnsRecordData trait", you need a generic:

    pub struct DnsPacket
    where
        D: DnsRecordData,
    {
        pub answers: Vec>,
    }
    

    Traits can be implemented, but they also have their own type. In order to create this type, the trait needs to be object-safe - Trait Object is not Object-safe error.

    As the error message states, this trait cannot be a trait object because there are generic types on the method.

    The first error states that DnsRecord requires that whatever type it is parameterized with must implement DnsRecordData. However, the type of the trait object doesn't actually implement that. Normally, you'd use a trait object via a reference (&dyn DnsRecordData) or a box (Box), both of which should implement the trait, preventing this error.

提交回复
热议问题