代码之家  ›  专栏  ›  技术社区  ›  Riduidel

为什么在方法签名中使用hyper::Client时会出现错误“类型参数的数目错误”?

  •  0
  • Riduidel  · 技术社区  · 6 年前

    hyper::Client 根据URL方案配置。为此,我创建了一个小方法:

    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
    

    我不明白为什么不编译

    • 我声明在文件头中使用

    2 回复  |  直到 6 年前
        1
  •  2
  •   Shepmaster Tim Diekmann    6 年前

    看看 documentation for Client : 是一个 generic type 这取决于两个类型参数:连接器类型 C 以及可选的体型 B 顾客 你返回,除了在你的特定情况下,它看起来你想返回 Client<HttpConnector> 或者 Client<HttpsConnector>

    取决于您打算如何使用 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 { /* … */ }
    

    或者你可以定义一个特征,实现它 客户<HttpConnector> 客户<HttpsConnector> 并且拥有 获取客户

    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> { /* … */ }
    
        2
  •  2
  •   Shepmaster Tim Diekmann    6 年前

    hyper::Client 接受类型参数。可以在关联的函数调用中忽略它们 Client::new() 因为编译器会推导出它们,但不会在函数签名中这样做。

    Client<HttpConnector, Body> .

    问题是,您的builder方法返回 Client<HttpsConnector, Body> ,这是不同的。您可能必须定义自己的特征才能通过连接器进行抽象。