简体   繁体   中英

Generic functions in Rust

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

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);
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM