简体   繁体   English

Rust 中的通用函数

[英]Generic functions in Rust

I would like create shared library (plugin) with generic function.我想创建具有通用功能的共享库(插件)。 T can be : u8, u16, u32, float, i8, i16, i32. T可以是:u8、u16、u32、浮点数、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.您需要在泛型类型 T 上指定一个 trait bound,见下文。 This requires that the type T implements the Display trait.这要求类型 T 实现 Display trait。 Here is a link to the Rust docs for this topic. 是指向该主题的 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);
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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