Clippy fix re borrowed Box not working?

I have a clippy suggestion ( here Font is a trait ):

---------- Clippy ----------
    Checking pdf-min v0.1.1 (C:\rust\pdf-min)
warning: you seem to be trying to use `&Box<T>`. Consider using just `&T`
  --> src\page.rs:65:34
   |
65 |     pub fn text(&mut self, font: &Box<dyn Font>, size: i16, s: &str) {
   |                                  ^^^^^^^^^^^^^^ help: try: `&dyn Font`
   |
   = note: `#[warn(clippy::borrowed_box)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrowed_box

warning: `pdf-min` (lib) generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.37s
Normal Termination
Output completed (0 sec consumed).

Source is here: Page in pdf_min::page - Rust

The trouble is, when I change it as suggested I get compilation errors:

---------- Check ----------
    Checking pdf-min v0.1.1 (C:\rust\pdf-min)
error[E0277]: the trait bound `Box<dyn font::Font>: font::Font` is not satisfied
   --> src\writer.rs:117:21
    |
117 |         self.p.text(f, self.font_size, s);
    |                     ^ the trait `font::Font` is not implemented for `Box<dyn font::Font>`
    |
    = help: the trait `font::Font` is implemented for `font::StandardFont`
    = note: required for the cast to the object type `dyn font::Font`

error[E0277]: the trait bound `Box<(dyn font::Font + 'static)>: font::Font` is not satisfied
   --> src\writer.rs:167:17
    |
167 |                 &self.fonts[0],
    |                 ^^^^^^^^^^^^^^ the trait `font::Font` is not implemented for `Box<(dyn font::Font + 'static)>`
    |
    = help: the trait `font::Font` is implemented for `font::StandardFont`
    = note: required for the cast to the object type `dyn font::Font`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `pdf-min` due to 2 previous errors
Normal Termination
Output completed (0 sec consumed).

I cannot figure out how to keep Clippy happy!

At a guess, you could do one of...

  • pass &*self.fonts[0] to turn a &Box<dyn Font> into a &dyn Font
  • implement Font for Box<dyn Font> (or Box<dyn Font + '_>)
    • with a chance of indirection... which you already had with &Box<dyn Font>
  • Ignore clippy :wink:

I figured your first suggestion out ( which works ) just before you replied.

I never ignore clippy!

Edit: I do think the error message could be more helpful in situations where all that is needed is a &*.

I haven't had to do this for a while, and forgot it is sometimes necessary.

3 Likes

Please file a ticket with this request at Issues · rust-lang/rust · GitHub :slight_smile:

2 Likes

Ok: Error message for missing * could be more helpful · Issue #101721 · rust-lang/rust · GitHub

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.