![](/img/trans.png)
[英]How can I use enum in a trait and implement trait on structs that are in the enum? Rust
[英]How can I implement a trait in scope for an enum of existing types for which the trait is implemented?
如何為實現該特征的現有類型的枚舉實現范圍內的特征?
我有這個:
extern crate pnet;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::ipv6::Ipv6Packet;
enum EthernetType {
IPv4,
ARP,
VLAN,
IPv6,
Unknown(u16),
}
enum IPPacket<'a> {
IPv4(Ipv4Packet<'a>),
IPv6(Ipv6Packet<'a>),
}
fn ip_decode(pkt: &[u8]) -> IPPacket {
let version = (pkt[0] & 0xf0) >> 4;
if version == 4 {
IPPacket::IPv4(Ipv4Packet::new(&pkt).unwrap())
} else {
IPPacket::IPv6(Ipv6Packet::new(&pkt).unwrap())
}
}
fn main() {
// Parse ethernet packet here...
// ...
let ip_packet = ip_decode(b"deadbeef");
println!("{:?}", ip_packet.payload());
}
編譯器抱怨我沒有為我的枚舉實現Packet
特性 :
error[E0599]: no method named `payload` found for type `IPPacket<'_>` in the current scope
--> src/main.rs:32:32
|
14 | enum IPPacket<'a> {
| ----------------- method `payload` not found for this
...
32 | println!("{:?}", ip_packet.payload());
| ^^^^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `payload`, perhaps you need to implement it:
candidate #1: `pnet::packet::Packet`
我以為Packet
特質將通過Ipv4Packet<'a>
和Ipv6Packet<'a>
派生出來?
如何為現有類型的枚舉實現范圍內的特征
您為枚舉實現特征的方式與為結構實現特征的方式相同:
trait Noise {
fn noise(&self);
}
enum Foo {
Bar,
Baz,
}
impl Noise for Foo {
fn noise(&self) {
match self {
Foo::Bar => println!("bar bar bar"),
Foo::Baz => println!("baz baz baz"),
}
}
}
已實現特征的現有類型的枚舉
我以為
Packet
特質會得到
它不是。 這樣做會阻止人們在需要時實現自己的特征代碼。 它也不能在所有情況下都起作用,例如當一個變體沒有實現它時。
trait Noise {
fn noise(&self);
}
struct Bar;
impl Noise for Bar {
fn noise(&self) {
println!("bar bar bar");
}
}
struct Baz;
impl Noise for Baz {
fn noise(&self) {
println!("baz baz baz");
}
}
enum Foo {
Bar(Bar),
Baz(Baz),
}
impl Noise for Foo {
fn noise(&self) {
match self {
Foo::Bar(bar) => bar.noise(),
Foo::Baz(baz) => baz.noise(),
}
}
}
從概念上講,可以對該語言進行擴展以支持某些注釋來執行此操作,但是我從未聽說有人建議這樣做。 您可以考慮創建一個RFC來添加它。
也許您可以回到教導您的信息源,並從根本上糾正問題,以防止其他人以相同的方式感到困惑。
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.