How to implement a trait for a parameterized trait

别说谁变了你拦得住时间么 提交于 2019-11-28 13:39:15

Here’s an implementation using associated types (which means that you can only implement MyTrait for one K per type):

use std::fmt;

pub trait MyTrait {
    type K: fmt::Display;
    fn get_some_k(&self) -> Option<Self::K>;
}

impl<S: MyTrait> fmt::Display for S {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_some_k().unwrap())
    }
}

fn main() { }

However, when clarified like this it becomes clear that this approach won’t work either, because you’re implementing Display for all types that implement MyTrait—types that could have their own Display implementation. This is forbidden, and so you get E0210:

error: type parameter S must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter [E0210]

Wrapping it in something—like your Ugly did—is the only way to allow such an implementation. Or implement a trait in your own crate rather than one in someone else’s (like Display is).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!