[英]Implementing trait methods for specific types
I'm trying to create a Coder trait with two methods (encode and decode).我正在尝试使用两种方法(编码和解码)创建 Coder 特征。 Each implementation of the trait needs to deal only with a specific type of input/output, so for instance:
特征的每个实现只需要处理特定类型的输入/输出,例如:
Approach 1: a simple way to satisfy the compiler would be to make encode and decode accept Any, and have each implementation deal with it separately.方法 1:满足编译器的一种简单方法是让编码和解码接受 Any,并让每个实现分别处理它。 This seems like a bad idea since each coder should only deal with a single type.
这似乎是个坏主意,因为每个编码员应该只处理一种类型。
type SomeEncodableHopefully = Box<dyn std::any::Any>;
pub trait Coder {
fn encode(&self, element: SomeEncodableHopefully) -> &[u8];
fn decode(&self, bytes: &[u8]) -> SomeEncodableHopefully;
}
pub struct BytesCoder {
...
}
impl BytesCoder {
pub fn new() -> Self {
...
}
}
impl Coder for BytesCoder {]
// "element" should only be &[u8] instead of Any
fn encode(&self, element: SomeEncodableHopefully) -> &[u8] {
...
}
// The output shouldn't be Any either
fn decode(&self, bytes: &[u8]) -> SomeEncodableHopefully {
...
}
}
pub struct KVCoder {
...
}
impl KVCoder {
pub fn new() -> Self {
...
}
}
impl Coder for KVCoder {]
// "element" should only be HashMap<...> instead of Any
fn encode(&self, element: SomeEncodableHopefully) -> &[u8] {
...
}
// The output shouldn't be Any either
fn decode(&self, bytes: &[u8]) -> SomeEncodableHopefully {
...
}
}
fn test_coder(coder: Box<dyn Coder>, to_encode: SomeEncodableHopefully, to_decode: &[u8]) {
let encoded:&[u8] = coder.encode(to_encode);
let decoded:SomeEncodableHopefully = coder.decode(to_decode);
}
Approach 2: I tried to use an associated type, but I wasn't able to succesfully define a fixed type for each implementation of Coder:方法 2:我尝试使用关联类型,但无法为 Coder 的每个实现成功定义固定类型:
pub trait Coder {
// The compiler ignores Element on each implementation and requires
// this to be defined manually when a coder is used
type Element;
fn encode(&self, element: Self::Element) -> &[u8];
fn decode(&self, bytes: &[u8]) -> Self::Element;
}
...
impl Coder for BytesCoder {
// This gets ignored
type Element = &[u8];
fn encode(&self, element: Self::Element) -> &[u8] {
...
}
fn decode(&self, bytes: &[u8]) -> Self::Element {
...
}
}
...
// Error on coder: the value of the associated type `Element` (from trait `Coder`) must be specified
fn test_coder(coder: Box<dyn Coder>, to_encode: SomeEncodableHopefully, to_decode: &[u8]) {
let encoded:&[u8] = coder.encode(to_encode);
let decoded:SomeEncodableHopefully = coder.decode(to_decode);
}
Approach 3: it could be a good idea to define type-specific versions of encode and decode.方法 3:定义特定类型的编码和解码版本可能是个好主意。 I had no complaints from the compiler, but this would be pretty verbose if there are many types involved (including, for instance: HashMap<A,B>, HashMap<A,C>, ...):
我没有收到编译器的投诉,但如果涉及许多类型(包括,例如:HashMap<A,B>、HashMap<A,C>,...),这将非常冗长:
pub trait Coder {
fn encode_to_bytes(&self, element: &[u8]) -> &[u8] {
panic!("Invalid operation for this type of coder");
}
fn decode_to_bytes(&self, bytes: &[u8]) -> &[u8] {
panic!("Invalid operation for this type of coder");
}
fn encode_to_some_other_type (&self, element: SomeOtherType) -> &[u8] {
panic!("Invalid operation for this type of coder");
}
fn decode_to_some_other_type (&self, bytes: &[u8]) -> SomeOtherType {
panic!("Invalid operation for this type of coder");
}
}
...
// Ok
impl Coder for BytesCoder {
fn encode_to_bytes(&self, element: &[u8]) -> &[u8] {
...
}
fn decode_to_bytes(&self, bytes: &[u8]) -> &[u8] {
...
}
}
...
The third approach seems to solve the problem somewhat decently, but is there a better way to achieve this?第三种方法似乎有点体面地解决了问题,但是有没有更好的方法来实现这一点?
The error of your second approach requests you to specify the type of Coder
it has to match with the type of to_encode
for this to work.第二种方法的错误要求您指定
Coder
的类型,它必须与to_encode
的类型匹配才能工作。 I introduce a generic here to make it as flexible as possible.我在这里引入一个泛型,以使其尽可能灵活。
fn test_coder<E>(coder: Box<dyn Coder<Element = E>>, to_encode: E, to_decode: &[u8]) {
let encoded: &[u8] = coder.encode(to_encode);
let decoded: E = coder.decode(to_decode);
}
Which leaves open the question of who owns your slices that SirDarius raised.这留下了 SirDarius 提出的谁拥有您的切片的问题。 You probably should return an owned type instead since generally you can't take a
&[u8]
from every type:您可能应该返回一个拥有的类型,因为通常您不能从每种类型中获取
&[u8]
:
pub trait Coder {
type Element;
fn encode(&self, element: Self::Element) -> Vec<u8>;
fn decode(&self, bytes: &[u8]) -> Self::Element;
}
struct BytesCoder;
type SomeEncodableHopefully = Vec<u8>;
impl Coder for BytesCoder {
type Element = Vec<u8>;
fn encode(&self, element: Self::Element) -> Vec<u8> {
element
}
fn decode(&self, bytes: &[u8]) -> Self::Element {
bytes.to_vec()
}
}
If Element
has to be a reference you can use a GAT in it's stead.如果
Element
必须是引用,您可以使用 GAT 代替。 Or make the trait take a lifetime.或者让这个特质持续一生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.