generics - Rust 中的泛型函数

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

错误:

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

相关文章:

generics - 在Scala中可转换为结构类型的通用方法

rust - 无法移出 Rust 中的借用内容

rust - 为什么我会收到错误 "function pointers in const fn are unstable",但在用新类型包装后它会消失?

compiler-errors - 闭包——移动值的使用

Java 泛型 : Casting a raw type to any reifiable type doesn't generate unchecked cast warning

c# - 将类泛型类型约束为元组

java - JVM 是否有计划在运行时支持泛型?

java - Java 中的通用 addListener

string - 预期结构 `std::string::String`,找到结构 `std::str::Split`

makefile - `make` 没有注意到 Rust 模块中的修改 - 如何更好地将 Rust 集成到构建中?