这是我已经纠结了一段时间的代码
use ethers_providers::{Provider, Http}; //, JsonRpcClient};
// this doesn't work
// trait ClientGeneric<T> {
// fn get_client(&self, url:&str) -> Provider<T> {
// Provider::<T>::try_from(url).unwrap()
// }
// }
// this works but I want generic
trait ClientConcrete {
fn get_client(&self, url:&str) -> Provider<Http> {
Provider::<Http>::try_from(url).unwrap()
}
}
struct Test;
impl ClientConcrete for Test {}
#[cfg( test )]
mod tests {
use super::*;
// #[test]
// fn test_get_client_generic() {
// let test = Test{};
// let client = test.get_client("http://localhost:8080");
// }
#[test]
fn test_get_client_concrete() {
let test = Test{};
let client = test.get_client("http://localhost:8080");
}
}
我希望 for each 传输T返回Provider<T>
:http、ws、ipc、mock等
通常,每个传输都实现了TryFrom特征.然而,上面的代码不适用于泛型T,即使它适用于具体的传输.对于泛型T,我收到的错误:
error[E0277]: the trait bound `Provider<T>: From<&str>` is not satisfied
--> src/test.rs:6:9
|
6 | Provider::<T>::try_from(url).unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `From<&str>` is not implemented for `Provider<T>`
|
= help: the following other types implement trait `TryFrom<T>`:
<Provider<Http> as TryFrom<&'a String>>
<Provider<Http> as TryFrom<&str>>
<Provider<Http> as TryFrom<String>>
= note: required because of the requirements on the impl of `Into<Provider<T>>` for `&str`
= note: required because of the requirements on the impl of `TryFrom<&str>` for `Provider<T>`
不幸的是,在类型T上没有匹配语句,我可以使用(就像在Golang中一样)来实现具体的类型.
据我所知,我不能为外来 struct Provider<T>
实现外来特性TryFrom<&str>
.TryFrom<&str>
是为基础类型Http
、Ws
、Ipc
等实现的
还有什么我能做的吗?