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

前端 未结 2 1991
野性不改
野性不改 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:21

    The error comes from the fact that you can't create trait objects for DnsRecordData due to the trait not being "object-safe". This concept is explained in the trait objects section of The Rust Programming Language.

    In your particular case, the trait contains a generic method. To create a trait object, the compiler has to synthesize a vtable for the trait, containing a function pointer for every method the trait has. But because the trait has a generic method, it effectively has as many methods as the method could be instantiated with, which is potentially infinite. Therefore, you cannot make a trait object for DnsRecordData.

提交回复
热议问题