我有一个设计问题,当使用类似的东西时:
trait MyTrait<K: OtherTrait> { ... }
impl<K: OtherTrait, M: MyTrait<K>> AnyTrait for M { ... }
Run Code Online (Sandbox Code Playgroud)
由于E207错误("类型参数K不受impl trait,self type或谓词"约束),我无法为此特征实现特征.
找不到摆脱这个错误,我应用这个不那么好看的解决方法(详细和结构没有内在价值):
use std::fmt;
use std::marker::PhantomData;
pub trait MyTrait<K: fmt::Display> {
fn get_some_k(&self) -> Option<K>;
}
/* // This is my target impl but results in E207 due to K not constrained
impl<K: fmt::Display, S: MyTrait<K>> fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.get_some_k().unwrap())
}
} */
pub struct Ugly<'a, …Run Code Online (Sandbox Code Playgroud) 我对某些代码有点困惑,http://is.gd/OMvnN7:每晚的错误修复使其无效(有充分的理由:https://github.com/rust-lang/rust/pull/24461) ,但我没有看到任何替代方法可以让我的代码运行。
关键是我的关联类型“SignedContent”大多数时候都有一个关联的生命周期,但我不想将此生命周期绑定到其父特征(对现有代码的影响可能是每个使用此特征的特征(很多) )将需要一个额外的生命周期参数,这看起来不太实用)。
我可能会结束切换到直接返回的“get_sign_content” Vec<u8>,但我真的更喜欢返回可编码的结构。
唯一缺少的是表达我的关联类型生命周期界限与其父级相同,类似的东西(无效)
impl TrustedVal for RSAPeer
{
type SignedContent = TrustedPeerToSignEnc<'Self::lifetime>;
Run Code Online (Sandbox Code Playgroud)
或者
impl<'a> TrustedVal for RSAPeer where RSAPeer : 'a
{
type SignedContent = TrustedPeerToSignEnc<'a>;
Run Code Online (Sandbox Code Playgroud)
我也考虑(这是有效的)
impl<'a> TrustedVal for &'a RSAPeer
{
type SignedContent = TrustedPeerToSignEnc<'a>;
Run Code Online (Sandbox Code Playgroud)
但与其他一些代码相比,它变得非常尴尬。关于设计这个的正确方法有什么想法吗?
此代码简化了更复杂的代码以隔离问题:
use std::marker::PhantomData;
pub trait ExtWrite {
fn write_end<W>(&mut self, &mut W);
}
pub struct ST;
impl ExtWrite for ST {
fn write_end<W>(&mut self, _: &mut W) {}
}
struct MCW<'a, 'b, W: 'a, EW: 'b + ExtWrite>(&'a mut W, &'b mut [EW]);
impl<'a, 'b, W: 'a, EW: 'b + ExtWrite> MCW<'a, 'b, W, EW> {
fn write_end_all(&mut self) {
if let Some((f, last)) = self.1.split_first_mut() {
let mut el = MCW(self.0, last);
f.write_end(&mut el);
// do on current el.write_end(); …Run Code Online (Sandbox Code Playgroud)