0

I want to create a structure called Timeout that is exactly std::time::Duration but implement Display trait for it.

Background

I want to use the query_params crate on my structure that looks like:

#[macro_use]
extern crate query_params;
use std::time::Duration;

#[derive(QueryParams)]
struct PullRequestsParametersApi {
    page: Option<i32>,
    timeout: Option<Duration>,
}

fn main() {
    let pr = PullRequestsParametersApi {
        page: Some(32),
        timeout: None,
    };

    println!("Query=  {} <<end", pr.to_query_params());
}

This causes a compiler error:

--> src/main.rs:5:10
  |
5 | #[derive(QueryParams)]
  |          ^^^^^^^^^^^ `std::time::Duration` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
  |
  = help: the trait `std::fmt::Display` is not implemented for `std::time::Duration`
  = note: required because of the requirements on the impl of `std::fmt::Display` for `&std::time::Duration`
  = note: required by `std::fmt::Display::fmt`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
S.R
  • 2,411
  • 1
  • 22
  • 33
  • See also: https://stackoverflow.com/q/30633177/155423, https://stackoverflow.com/q/43081345/155423, https://stackoverflow.com/q/22243527/155423. – Shepmaster Jan 21 '18 at 17:51
  • @Shepmaster it complains that there is no such method like `as secs` `write!(f, "{}", self.as_secs())`. But it exist in `std::time::Durration` look [here](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs) – S.R Jan 21 '18 at 18:03
  • Please carefully read the duplicate answers: `// use \`self.0\` here`. Not just `self`. – Shepmaster Jan 21 '18 at 18:03
  • I read it twice. And make a test with `struct Timeout(std::time::Duration);` and `struct Timeout { timeout:std::time::Duration}` the second compile fine. (Of course for second there is `write!(f, "{}", self.timeout.as_secs())`) So I don't get it :/ – S.R Jan 21 '18 at 18:12
  • 1
    `write!(f, "{}", self.0.as_secs())` not `write!(f, "{}", self.as_secs())`. **self.0**.as_secs() not **self**.as_secs(). `self.0` not `self` — I don't know how to say it any differently, I'm sorry. – Shepmaster Jan 21 '18 at 18:14
  • Oh. I get it. But this is just more complex. If I need to write `0` is better to use `timeout` that meaning at least sth :) – S.R Jan 21 '18 at 18:16

0 Answers0