我想获得一个根据 URL 方案配置的 hyper::Client
。为此,我创建了一个小方法:
extern crate http; // 0.1.8
extern crate hyper; // 0.12.7
extern crate hyper_tls; // 0.1.4
use http::uri::Scheme;
use hyper::{Body, Client, Uri};
use hyper_tls::HttpsConnector;
#[derive(Clone, Debug)]
pub struct Feed;
impl Feed {
fn get_client(uri: Uri) -> Client {
match uri.scheme_part() {
Some(Scheme::HTTP) => Client::new(),
Some(Scheme::HTTPS) => {
let https = HttpsConnector::new(4).expect("TLS initialization failed");
let client = Client::builder().build::<_, Body>(https);
}
_ => panic!("We don't support schemes other than HTTP/HTTPS"),
}
}
}
当我尝试编译它时,我收到此错误消息:
error[E0243]: wrong number of type arguments: expected at least 1, found 0
--> src/main.rs:13:32
|
13 | fn get_client(uri: Uri) -> Client {
| ^^^^^^ expected at least 1 type argument
我不明白为什么它不能编译,因为
- 我已经在我的 main.rs 中声明了我使用 hyper crate
- 我在文件头声明我的用途
我做错了什么?
最佳答案
查看documentation for Client
: Client
是 generic type这取决于两个类型参数:连接器类型 C
和一个可选的 body 类型 B
.您需要指定哪些类型参数适用于 Client
你返回,除了在你的特定情况下它看起来像你想要返回 Client<HttpConnector>
或 Client<HttpsConnector>
取决于 URI 方案。你不能那样做,期间。
取决于您打算如何使用您的 get_client
函数,您可以将返回值包装在 enum
中:
enum MyClient {
HttpClient (Client<HttpConnector>),
HttpsClient (Client<HttpsConnector>),
}
impl MyClient {
pub fn get(&self, uri: Uri) -> ResponseFuture {
match self {
HttpClient (c) => c.get (uri),
HttpsClient (c) => c.get (uri),
}
}
}
fn get_client(uri: Uri) -> MyClient { /* … */ }
或者你可以定义一个特征,为Client<HttpConnector>
实现它和 Client<HttpsConnector>
并且有get_client
返回你的特征的盒装实例,比如:
trait MyClient {
pub fn get(&self, uri: Uri) -> ResponseFuture;
}
impl<C> MyClient for Client<C> {
pub fn get(&self, uri: Uri) -> ResponseFuture {
Client<C>::get (&self, uri)
}
}
fn get_client(uri: Uri) -> Box<MyClient> { /* … */ }
关于compiler-errors - 为什么在方法签名中使用 hyper::Client 时会出现错误 "wrong number of type arguments"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841791/