compiler-errors - 为什么在方法签名中使用 hyper::Client 时会出现错误 "wrong number of type arguments"?

标签 compiler-errors rust hyper

我想获得一个根据 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 : Clientgeneric 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/

相关文章:

visual-studio - 在Visual Studio编辑器中可视化错误位置

multithreading - 接收器在尝试通过 channel 发送时关闭并返回 SendError

c - 尝试编译讲师的程序时出错(定义行中预期的符号)

arrays - 从切片构建数组的正确方法?

arrays - 初始化固定长度数组的正确方法是什么?

ssl - Hyper 表示 "Invalid scheme for Http"用于 HTTPS URL

async-await - 如何使用 Rust 中新的异步等待语法通过 H2 执行 HTTP2 请求?

rust - 如何在稳定的 Rust 中同步返回在异步 Future 中计算的值?

objective-c - 为什么我在正确链接框架时会收到 "_OBJC_CLASS_$..., referenced from:"链接器错误?

c# - 已经定义了InitializeComponent和contentLoaded之间的歧义