How to write a trait bound for a reference to an associated type on the trait itself?

两盒软妹~` 提交于 2019-12-18 09:08:21

问题


I have this code:

extern crate serde;

use serde::de::DeserializeOwned;
use serde::Serialize;

trait Bar<'a, T: 'a>
where
    T: Serialize,
    &'a T: DeserializeOwned,
{
}

I would like to write this using an associated type, because the type T is unimportant to the users of this type. I got this far:

trait Bar {
    type T: Serialize;
}

I cannot figure out how to specify the other bound.

Ultimately, I want to use a function like this:

extern crate serde_json;

fn test<I: Bar>(t: I::T) -> String {
    serde_json::to_string(&t).unwrap()
}

回答1:


The "correct" solution is to place the bounds on the trait, but referencing the associated type. In this case, you can also use higher ranked trait bounds to handle the reference:

trait Bar
where
    Self::T: Serialize,
//  ^^^^^^^ Bounds on an associated type  
    for<'a> &'a Self::T: DeserializeOwned,
//  ^^^^^^^^^^^ Higher-ranked trait bounds       
{
    type T;
}

However, this doesn't work yet.

I believe that you will need to either:

  • wait for issue 20671 and/or issue 50346 to be fixed.
  • wait for the generic associated types feature which introduces where clauses on associated types.

In the meantime, the workaround is to duplicate the bound everywhere it's needed:

fn test<I: Bar>(t: I::T) -> String
where
    for<'a> &'a I::T: DeserializeOwned,
{
    serde_json::to_string(&t).unwrap()
}


来源:https://stackoverflow.com/questions/50090578/how-to-write-a-trait-bound-for-a-reference-to-an-associated-type-on-the-trait-it

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