首页 > 解决方案 > 如何缩短长的where子句?

问题描述

我有这个声明:

impl<T: JobContext, R> TaskProcessor<T, R>
where
    R: hyper::service::Service<hyper::client::connect::dns::Name> + Clone + Send + Sync + 'static,
    R::Response: std::iter::Iterator<Item = std::net::SocketAddr>,
    R::Future: Send,
    R::Error: std::error::Error + Send + Sync,
{
}

我想将条件转移where到它自己的特征中,这样我就可以写如下内容:

impl<T: JobContext, R: DnsResolve> TaskProcessor<T, R> { }

做这个的最好方式是什么?

标签: genericsrust

解决方案


以下解决了我的问题

trait DnsResolve: hyper::service::Service<hyper::client::connect::dns::Name, Response: std::iter::Iterator<Item = std::net::SocketAddr>, Future: Send, Error: std::error::Error + Send + Sync> + Clone + Send + Sync + 'static
{
}

impl<T> DnsResolve for T where T: hyper::service::Service<hyper::client::connect::dns::Name, Response: std::iter::Iterator<Item = std::net::SocketAddr>, Future: Send, Error: std::error::Error + Send + Sync> + Clone + Send + Sync + 'static,
{
}

但这使用了不稳定的功能

https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html

https://github.com/rust-lang/rust/issues/52662

而且我不得不使用 nightly rustc 编译我的代码......我不太喜欢

这个话题对我来说很复杂,有什么办法可以绕过稳定生锈的相关类型界限吗?


推荐阅读