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**
**-->** src/lib.rs:51:6
**|**
**51** **|** impl<T> Context {
**|** **^** **unconstrained type parameter**
I have some few questions:
- Why I have to bound that generic param to something?
- How can I bound it to the Serde traits to ensure it can be parsed?
Thanks!