Rust 中的泛型函数

Mic*_*sek 2 generics rust

我想创建具有通用功能的共享库(插件)。 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误:

   |
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```

Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 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);
      }
}
Run Code Online (Sandbox Code Playgroud)