I've got this simplified Rust code:
use std::io::Result;
pub trait PacketBuffer {}
pub trait DnsRecordData {
fn write<T: PacketBuffer>(&self, buffer: &mut T) -> Result<usize>;
}
pub struct DnsRecord<R: DnsRecordData + ?Sized> {
pub data: Box<R>,
}
pub struct DnsPacket {
pub answers: Vec<DnsRecord<dyn DnsRecordData>>,
}
The intention is that DnsRecord
should be able to hold any struct implementing the DnsRecordData
trait, with the different structs representing A, AAAA, CNAME etc.
This fails with the error:
error[E0038]: the trait `DnsRecordData` cannot be made into an object
--> src/lib.rs:14:5
|
14 | pub answers: Vec<DnsRecord<dyn DnsRecordData>>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `DnsRecordData` cannot be made into an object
|
= note: method `write` has generic type parameters
What's got me the most confused is that by removing the generics from DnsRecordData::write()
, it compiles just fine:
use std::io::Result;
pub trait PacketBuffer {}
pub trait DnsRecordData {
fn write(&self, buffer: &mut dyn PacketBuffer) -> Result<usize>;
}
pub struct DnsRecord<R: DnsRecordData + ?Sized> {
pub data: Box<R>,
}
pub struct DnsPacket {
pub answers: Vec<DnsRecord<dyn DnsRecordData>>,
}
If anyone can explain what I'm missing, I'd very much appreciate it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…