Need help with parsing function

Hello there!

As an educational exercise, I’m building a Rust HTTP Client of a REST API. In order to DRY up my code, I would like to have a function that receives the essentials for making a request and also the knowledge for parsing it. Therefore, I am trying to use type generics. Here is the code:

impl<T> Context {
    pub fn perform_request<T>(
        &self,
        method: &str,
        url: &str,
        body: &str,
        headers: HashMap<String, String>,
        parse_fn: fn(hyper::Chunk) -> T
      ) {
            tokio::run(future::lazy(|| {
                let https = HttpsConnector::new(4).unwrap();
                let client = Client::builder().build::<_, hyper::Body>(https);
                // omitting build_request function.
                let request = build_request(String::from(method),
                    String::from(url),
                    String::from(body),
                    &headers);
                    client.request(request).and_then(|res: Response<Body>| {
                        res.into_body().concat2()
                    }).map_err(|err| {
                            println!("ERROR!");
                            println!("{:?}", err);
                    }).map(parse_fn)
                }));
        }
}

Basically, I’ve trying to bound it to the Serde traits because I am getting the following error:

**error[E0207]** **: the type parameter `T` is not constrained by the impl trait, self type, or predicates**

**--&gt;** src/lib.rs:51:6

**|**

**51** **|** impl&lt;T&gt; Context {

**|** **^** **unconstrained type parameter**

I have some few questions:

  1. Why I have to bound that generic param to something?
  2. How can I bound it to the Serde traits to ensure it can be parsed?

Thanks!

I may not be able to understand what you want, the solution for your issue depends on your situation.

If Context has member variables related to T like data: T, data: Vec<T> and so on (that means 'Contexthas the generic parameterT`), you have to write like below:

impl<T> Context<T> {                         // Context -> Context<T>
    pub fn perform_request(...) -> T { ... } // perform_request<T> -> perform_request
}

If not (that means Context has no generic parameter and perform_request has the generic parameter T), you have to write like below:

impl Context {  // imp<T> -> impl
    pub fn perform_request<T>(...) -> T { ... }
}

See “3.18. Generics” in TRPL for details.