首页 > 解决方案 > 在 Rust 中使用 if 语句时的不同函数类型

问题描述

我是 rust 新手,我需要在函数选项上做一个小的 if 语句,例如

use isahc::{
    HttpClient, 
    config::{
        RedirectPolicy, 
        VersionNegotiation,
        SslOption}, 
    prelude::*
};

use std::{
    time::Duration
};

pub struct http {
    pub timeout: u64    
}





impl http {
    pub fn send(&self) -> HttpClient  {
        let client = 
            HttpClient::builder()
                .version_negotiation(VersionNegotiation::http11())
                .redirect_policy(RedirectPolicy::None)
                .timeout(Duration::from_secs(self.timeout));
                .ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS | SslOption::DANGER_ACCEPT_REVOKED_CERTS);
        return client.build().unwrap();
    }

    }

fn main(){
    let req = http{ timeout:"20".parse().unwrap()};
    let test = req.send();
    test.get("https://www.google.com");
}

现在在我的程序中,用户会给我请求的选项(例如:是否遵循重定向)并且需要if statement这些选项,所以我尝试在这种情况下使用它,但我总是得到不同的函数返回类型

impl http {
    pub fn send(&self) -> HttpClient  {
        let client = 
            HttpClient::builder()
                .version_negotiation(VersionNegotiation::http11())
                .redirect_policy(RedirectPolicy::None)
                .ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS | SslOption::DANGER_ACCEPT_REVOKED_CERTS);
        if 1 == 1 {
            client.timeout(Duration::from_secs(self.timeout));
        }
        return client.build().unwrap();
    }

    }
warning: type `http` should have an upper camel case name
  --> src/sender.rs:14:12
   |
14 | pub struct http {
   |            ^^^^ help: convert the identifier to upper camel case: `Http`
   |
   = note: `#[warn(non_camel_case_types)]` on by default

error[E0382]: use of moved value: `client`
  --> src/sender.rs:32:16
   |
24 |         let client = 
   |             ------ move occurs because `client` has type `HttpClientBuilder`, which does not implement the `Copy` trait
...
30 |             client.timeout(Duration::from_secs(self.timeout));
   |             ------ value moved here
31 |         }
32 |         return client.build().unwrap();
   |                ^^^^^^ value used here after move

所以我做错了什么?我厌倦了更改函数类型异常,但我不能使用类的函数,client.get()例如

options : dict = {
  "redirects": False,
  "ssl_path":"~/cer.pem"
}


def send(opts):
   # not real httplib ! 
   r = httplib.get("http://stackoverflow.com")
   if opts.get('redirects') == True:
       r.redirects = True
   if opts.get('cert_path',''):
       r.ssl = opts.get('cert_path')
   return r.send()

def main():
   send(options)

谢谢

标签: if-statementrust

解决方案


由于这是一种构建器模式,因此每个函数调用都会使用构建器并将其返回。所以你需要client从函数的返回值中捕获timeout才能继续使用它。请注意,您还需要使client可变。

就像是

impl http {
    pub fn send(&self) -> HttpClient  {
        let mut client = 
            HttpClient::builder()
                .version_negotiation(VersionNegotiation::http11())
                .redirect_policy(RedirectPolicy::None)
                .ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS | SslOption::DANGER_ACCEPT_REVOKED_CERTS);
        if 1 == 1 {
            client = client.timeout(Duration::from_secs(self.timeout));
        }
        return client.build().unwrap();
    }
}

推荐阅读