我想创建具有通用功能的共享库(插件)。 T 可以是: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);
}
}
错误:
|
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```
最佳答案
正如评论者提到的。您需要在泛型类型 T 上指定特征绑定(bind),请参见下文。这要求类型 T 实现 Display 特征。 Here是指向此主题的 Rust 文档的链接。
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);
}
}
关于generics - Rust 中的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60115101/