如何在特征本身上为引用关联类型的特征写一个特征绑定? [英] How to write a trait bound for a reference to an associated type on the trait itself?

查看:167
本文介绍了如何在特征本身上为引用关联类型的特征写一个特征绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

extern crate serde;

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

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

我想使用关联类型来编写此代码,因为类型T对于该类型的用户而言并不重要.我走了这么远:

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()
}

推荐答案

正确"的解决方案是在特征上放置边界,但要引用关联的类型.在这种情况下,您还可以使用更高等级的特征范围来处理引用:

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;
}

但是,这还行不通.

我相信您将需要:

  • 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()
}

这篇关于如何在特征本身上为引用关联类型的特征写一个特征绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆