Reputation: 323
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```
Upvotes: 2
Views: 2088
Reputation: 929
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);
}
}
Upvotes: 5