2

I would like create shared library (plugin) with generic function. T can be : u8, u16, u32, float, i8, i16, i32.

pub struct Api {}
    impl Api {
        pub fn write_to_slave<T>(&self, id: u32, value: T)
        {
            println!("write to slave id : {}, value: {}", id, value);
        }
    }

Error:

   |
18 |     pub fn write_to_slave<T>(&self, id: u32, value: T)
   |                           - help: consider restricting this bound: `T: std::fmt::Display`
19 |     {
20 |         println!("write to slave id : {}, value: {}", id, value);
   |                                                           ^^^^^ `T` cannot be formatted with the default formatter
   |
   = help: the trait std::fmt::Display is not implemented for T
   = note: in format strings you may be able to use {:?} (or {:#?} for pretty-print) instead
   = note: required by std::fmt::Display::fmt```

1
  • 3
    Have you tried what the error message suggests to do? It helpfully shows you the exact trait bound you need to include to make this code compile. Commented Feb 7, 2020 at 16:14

1 Answer 1

5

As the commenter mentioned. You need to specify a trait bound on your generic type T, see below. This requires that the type T implements the Display trait. Here is a link to the Rust docs for this topic.

pub struct Api {}
impl Api {
   pub fn write_to_slave<T: Display>(&self, id: u32, value: T)
      {
         println!("write to slave id : {}, value: {}", id, value);
      }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.