gpt4 book ai didi

enums - 我如何在范围内为实现特征的现有类型的枚举实现特征?

转载 作者:行者123 更新时间:2023-11-29 08:26:51 25 4
gpt4 key购买 nike

如何在已实现特征的现有类型的枚举范围内实现特征?

我有这个:

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 trait对于我的枚举:

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>

最佳答案

How can I implement a trait in scope for an enum of existing types

为枚举实现特征的方式与为结构实现特征的方式相同:

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"),
}
}
}

an enum of existing types for which the trait is implemented

I thought that the Packet trait would be derived

事实并非如此。这样做会阻止人们在需要时为该特征实现他们自己的代码。它也不会在所有情况下都有效,例如当一个变体没有实现它时。

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 来添加它。

也许你可以回到教你这个的源头,从根本上纠正问题,以防止其他人以同样的方式感到困惑。

另见:

关于enums - 我如何在范围内为实现特征的现有类型的枚举实现特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com